字段初始值设定项不能引用非静态字段方法或 属性 'Component.GetComponent<Rigidbody>()'

a field initializer cannot reference the nonstatic field method or property 'Component.GetComponent<Rigidbody>()'

我不知道发生了什么,我正在尝试按照用 Unity 4 编写的教程进行操作,并且发生了很多变化。这是我所了解的,现在我被卡住了。

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    public static Rigidbody rb = GetComponent<Rigidbody>();
    private Vector3 input;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        GetComponent<Rigidbody>().AddForce(input);
    }
}

您不能在函数外使用 Unity 的 GetComponent 函数。把它放在一个函数中,你应该没问题。在这种情况下,将其放在 Start()Awake() 函数中是合适的。

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed;

    public static Rigidbody rb;
    private Vector3 input;

    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        GetComponent<Rigidbody>().AddForce(input);
    }
}