peperino boek
peperino boek

Reputation: 33

Unity An object reference is required to access non-static member C#

Im trying to learn C# with Unity engine

But a basic script like this:

using UnityEngine;
using System.Collections;

public class scriptBall : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Rigidbody.AddForce(0,1000f,0);
    }

    // Update is called once per frame
    void Update () {

    }
}

gives this error: Assets/Scripts/scriptBall.cs(8,27): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3, UnityEngine.ForceMode)'

i cant find a solution for my problem

Upvotes: 2

Views: 5139

Answers (2)

Andy M
Andy M

Reputation: 6065

You need to instantiate your class Rigidbody before accessing a non-static field such as AddForce.

From the documentation bellow :

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public float thrust;
    public Rigidbody rb;
    void Start() {
        // Get the instance here and stores it as a class member.
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate() {
        // Re-use the member to access the non-static method
        rb.AddForce(transform.forward * thrust);
    }
}

More here : http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

Upvotes: 3

Henry
Henry

Reputation: 2187

Add a local property to a rigid body and set it within the editor or use

var rigidBody = GetComponenet<RigidBody>();
rigidBody.Addforce(...)

to get the local instance of the component via code rather than the editor.

Upvotes: 0

Related Questions