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

久未见 提交于 2019-12-11 07:56:38

问题


I have no idea what is going on, I am trying to follow a tutorial that was written in Unity 4 and a lot has changed. This is as far as I have gotten and now I am stuck.

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);
    }
}

回答1:


You can't use Unity's GetComponent function outside a function. Put it in a function and you should be fine. In this is case, it is appropriate to put it in a Start() or Awake() function.

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);
    }
}


来源:https://stackoverflow.com/questions/39241408/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property-com

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!