【发布时间】:2019-06-16 14:44:15
【问题描述】:
所以我正在制作一个 Tamagotchi 宠物游戏,在统计数据中,“Void Update()”中的行似乎只更新了 _Happiness 中的第一行数据,而不是 _hunger 中的数据。有什么理由可能会发生这种情况吗?我的原型中还有另一个与统计数据相关的脚本。
public GameObject happinessText;
public GameObject hungerText;
public GameObject robot;
// Update is called once per frame
void Update()
{
happinessText.GetComponent<Text>().text = "" + robot.GetComponent<Robot>().happiness;
hungerText.GetComponent<Text>().text = "" + robot.GetComponent<Robot>().hunger;
//happinessText.GetComponent<Text>().text = "" + robot.GetComponent<Robot>().happiness;
}
其他脚本:
public int _hunger;
public int _happiness;
void Start()
{
PlayerPrefs.SetString("then", "05/06/2016 11:20:12");
updateStatus();
}
void updateStatus()
{
if (!PlayerPrefs.HasKey("_hunger"))
{
_hunger = 100;
PlayerPrefs.SetInt("_hunger", _hunger);
} else {
_hunger = PlayerPrefs.GetInt("_hunger");
}
if (!PlayerPrefs.HasKey("_happiness"))
{
_happiness = 100;
PlayerPrefs.SetInt("_happiness", _happiness);
} else {
_happiness = PlayerPrefs.GetInt("_happiness");
}
if (!PlayerPrefs.HasKey("then")) //{
PlayerPrefs.SetString("then", getStringTime());
TimeSpan ts = GetTimeSpan();
_hunger -= (int)(ts.TotalHours * 2);
if (_hunger < 0)
_hunger = 0;
_happiness -= (int)((100 - _hunger) * ts.TotalHours / 5);
if (_happiness < 0)
_happiness = 0;
}
public int hunger
{
[OnSerialized]
get { return _hunger; }
set { _hunger = value; }
}
public int happiness
{
[OnSerialized]
get { return _happiness; }
set { _happiness = value; }
}
【问题讨论】:
-
控制台是否显示任何错误?如果你切换两个语句,先调用饥饿语句,然后调用幸福语句,会发生什么?
-
如果
_hunger和_happiness仍然是公开的,您需要hunger和happiness字段吗? -
会发生什么?也许
hunger值根本没有改变? -
顺便说一句,不要在
Update中使用GetComponent.. 最好不要使用它:而不是GameObject引用使例如public Robot robot。 Unity 检查器将自动使用Robot组件作为参考 -
您的第一行抛出异常的可能原因。请确保对象不为空