Unity: An object reference is required for the non-static field, method, or property

Started by
0 comments, last by Agony 8 years, 5 months ago

Making a pong clone in Unity, had this error with the ball:

Severity Code Description Project File Line

Error CS0120 An object reference is required for the non-static field, method, or property 'Rigidbody2D.AddForce(Vector2)' Pong.CSharp C:\Users\Public\Documents\Unity Projects\Pong\Assets\BallControl.cs 27
Looked for other resources, and found this uses the same code: http://www.awesomeincu.com/tutorials/unity-pong/
What's going wrong?
Full Code:
What will you make?
Advertisement

Rigidbody2D, with an uppercase 'R', refers to a type. So any call of a member function with just a type is necessarily a static function call, which doesn't require an instance. But AddForce() is not a static function, and absolutely requires an instance.

Most likely, you want to use the instance of a Rigidbody2D class that is already attached to the same game object that your BallControl script is attached to. In earlier versions of Unity, you could simply access the rigidbody2D property (note the lowercase 'r') of the MonoBehavior base class. So simply using the lowercase 'r' instead of uppercase would fix the problem, as long as your game object did indeed have a Rigidbody2D component attached to it.

In newer versions of Unity, these properties were deprecated because they encouraged less performant code patterns. Instead, you should use the GetComponent<Rigidbody2D>() call that is a part of the MonoBehavior base class. And if you access this component on a regular basis in your script, it can be prudent to create a private field that will store a reference to the component, and initialize this field in your Start() method (or the Awake() method under some circumstances).


public class BallControl : MonoBehaviour
{
    int waitSeconds = 2;
    Rigidbody2D rigidbody2D;
 
    // Use this for initialization.
    void Start ()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        hi(20f);
        GoBall();
    }
 
    IEnumerator hi(float secs)
    {
        yield return new WaitForSeconds(secs);
    }
       
    // Generates random value, and decides which way to knock the ball based on it.
    void GoBall ()
    {
        float rand = Random.Range(0.0f, 100.0f);
 
        if (rand < 50.0f)
        {
            rigidbody2D.AddForce(new Vector2(20.0f, 15.0f));
        }
 
        else
        {
            rigidbody2D.AddForce(new Vector2(-20.0f, -15.0f));
        }
    }
}
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke

This topic is closed to new replies.

Advertisement