字段初始化程序无法引用非静态字段方法或属性'Component.GetComponent< Rigidbody>()' [英] a field initializer cannot reference the nonstatic field method or property 'Component.GetComponent<Rigidbody>()'
本文介绍了字段初始化程序无法引用非静态字段方法或属性'Component.GetComponent< Rigidbody>()'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道发生了什么,我正在尝试遵循Unity 4编写的教程,但发生了很多变化.据我所知,现在我被困住了.
I have no idea what is going on, I am trying to follow a tutorial that was written in Unity 4 and a lot has changed. This is as far as I have gotten and now I am stuck.
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public static Rigidbody rb = GetComponent<Rigidbody>();
private Vector3 input;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
GetComponent<Rigidbody>().AddForce(input);
}
}
推荐答案
您不能在函数外部使用Unity的GetComponent
函数.把它放在一个函数中就可以了.在这种情况下,最好将其放在Start()
或Awake()
函数中.
You can't use Unity's GetComponent
function outside a function. Put it in a function and you should be fine. In this is case, it is appropriate to put it in a Start()
or Awake()
function.
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public static Rigidbody rb;
private Vector3 input;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
GetComponent<Rigidbody>().AddForce(input);
}
}
这篇关于字段初始化程序无法引用非静态字段方法或属性'Component.GetComponent< Rigidbody>()'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文