You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#报错求助:Field Initializer无法引用非静态字段问题

Fixing "A Field Initializer cannot reference the nonstatic field..." Error in Unity

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 other Awake() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:48:34