unity3d 5.0 C#出错CS0120:访问非静态成员需要对象引用
问题描述:
在Unity 5.0中,由于我在下面写的代码,我得到以下错误。不幸的是,我不明白,任何人都可以帮忙吗?unity3d 5.0 C#出错CS0120:访问非静态成员需要对象引用
moneyGet.cs(19,17):错误CS0120:一个对象引用需要访问非静态成员`moneySystem.money '
using UnityEngine;
public class moneyGet : MonoBehaviour
{
int curHealth = 100;
int maxHealth = 100;
public void Update()
{
if (curHealth > maxHealth)
{
curHealth = maxHealth;
}
if (curHealth < 0)
{
curHealth = 0;
moneySystem.money += 100;//name of your script moneySystem
}
}
}
但是,下面的代码没有按'牛逼引发任何错误:
using UnityEngine;
public class moneySystem : MonoBehaviour
{
public int money = 0;//amout of your money
GUIText moneyText;//To Display Your money
void Update()
{
if (money < 0)
{
money = 0;
}
}
}
答
我不知道团结,所以我不能对整体设计进行评论,但像编译器会告诉你,你需要moneySystem
一个参考,因为它money
peroperty不是静态的。
因此,你可以在moneyGet
的构造函数实例化一个moneySystem
:
public class moneyGet
{
private moneySystem _moneySystem;
public moneyGet()
{
_moneySystem = new moneySystem();
}
}
然后在Update()
,你可以做_moneySystem.money += 100;
。
答
或者,根据游戏持续时间的预期上下文,您可以将您的moneySystem类设置为STATIC类,以便它始终可用于整个游戏时间,而不会“丢失”对象引用...使其上的属性也是静态的。
public static class moneySystem : MonoBehaviour {
public static int money = 0;//amout of your money
GUIText static moneyText;//To Display Your money
... rest of class...
然后,如果你有其他的元素,游戏场景等,你就不必担心试图实例他们,哎呀忘了,或者重新实例他们丢失任何以前的“钱”的价值观。
部分偏离主题,但这是代码标准派上用场的地方...... C#倾向于用骆驼套管和大写字母定义类,其中变量以较低的套管开始.. – Sayse 2015-03-25 11:27:55
个人而言,我讨厌当人们投票时没有理由。至于部分题外话,无视。你有一个合法的问题,在学习的同时,每个人都有自己的编码风格和命名约定。统一是奇怪的,因为你不知道对象创建的顺序,然后将“组件”添加到游戏对象中。我也在这个过程中学习。 – DRapp 2015-03-25 11:32:15
@DRapp - 我的downvote没有链接到我的评论。它与如果你[谷歌“访问非静态成员需要对象引用”](https://www.google.co.uk/search?q=An+object+reference+is+需要+到+访问+非静态+成员&ie = utf-8&oe = utf-8&gws_rd = cr&ei = 7JwSVfOgL4ae7gah1YGoAg)你会被充斥着重复的答案 – Sayse 2015-03-25 11:33:44