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

蹲街弑〆低调 提交于 2021-01-28 01:11:08

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30850751/unity-an-object-reference-is-required-to-access-non-static-member-c-sharp

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