本文介绍了unity 访问非静态成员C#需要一个对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Unity 引擎学习 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 () {

    }
}

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

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

推荐答案

在访问非静态字段(例如 AddForce)之前,您需要实例化您的类 Rigidbody.

You need to instantiate your class Rigidbody before accessing a non-static field such as 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

这篇关于unity 访问非静态成员C#需要一个对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:45