Travis Travis - 3 months ago 9
C# Question

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

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

Answer

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