简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM