Unity访问非静态成员C#需要对象引用

时间:2015-06-15 16:55:16

标签: c# unity3d

我试图用Unity引擎学习C#

但是像这样的基本脚本:

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 () {

    }
}

给出了这个错误: Assets / Scripts / scriptBall.cs(8,27):错误CS0120:访问非静态成员`UnityEngine.Rigidbody.AddForce(UnityEngine.Vector3,UnityEngine.ForceMode)'

需要对象引用

我无法找到解决问题的方法

2 个答案:

答案 0 :(得分:3)

在访问Rigidbody等非静态字段之前,您需要实例化您的班级AddForce

来自下面的文件:

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

更多信息:http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

答案 1 :(得分:0)

将一个本地属性添加到刚体并在编辑器中设置它或使用

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

通过代码而不是编辑器获取组件的本地实例。