Unity C#报错求助:Field Initializer无法引用非静态字段问题
Hey there! I totally get how confusing this error can be when you're just starting out with Unity—let's get this sorted for you.
What's causing the error?
The problem here is that you're trying to call GetComponent<Rigidbody2D>() directly when declaring your class field, like this:
// ❌ Wrong approach private Rigidbody2D myRb = GetComponent<Rigidbody2D>();
Unity hasn't finished setting up your GameObject and its components yet during the field initialization phase. That means non-static methods like GetComponent() aren't available to use at this point—hence the error message.
How to fix it
You need to move the GetComponent call into one of Unity's lifecycle initialization methods, where the object is fully set up and ready to access its components. The two most common choices are:
Awake(): Runs when the object is first created (great for early setup that needs to happen before other scripts run)Start(): Runs just before the first frame update (good if you need to wait for otherAwake()calls to finish first)
Here's what the corrected code looks like:
public class YourScriptName : MonoBehaviour { // Declare the field without initializing it here private Rigidbody2D myRb; void Awake() { // Now we can safely get the component myRb = GetComponent<Rigidbody2D>(); // Optional: Add a check to make sure we found the component if (myRb == null) { Debug.LogError("No Rigidbody2D found on this GameObject!"); } } // Your other methods (Update, FixedUpdate, etc.) go here void Update() { // Now you can use myRb in your logic if (myRb != null) { // Example: Add force to the rigidbody myRb.AddForce(Vector2.right * 5f); } } }
Quick extra tip
Make sure the Rigidbody2D component is attached to the same GameObject as your script. If it's on a child object, you can use GetComponentInChildren<Rigidbody2D>() instead, but for most beginner tutorials, they'll be on the same object.
内容的提问来源于stack exchange,提问作者Eve S

