【问题标题】:2018 Unity Void Update () not updating second line?2018 Unity Void Update()不更新第二行?
【发布时间】: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 仍然是公开的,您需要hungerhappiness 字段吗?
  • 会发生什么?也许hunger 值根本没有改变?
  • 顺便说一句,不要在Update 中使用GetComponent .. 最好不要使用它:而不是GameObject 引用使例如public Robot robot。 Unity 检查器将自动使用 Robot 组件作为参考
  • 您的第一行抛出异常的可能原因。请确保对象不为空

标签: c# unity3d int


【解决方案1】:

似乎updateStatus方法只被调用一次,在Other Script的Start方法中。

查看您的脚本,您似乎可能缺少Update() 函数:

void Update()
{
    updateStatus();
}

我还会在更新_hunger_happiness 的代码中放置一些断点。或者,如果您愿意,可以在那里拨打几个Debug.Log(...) 电话。重要的是要确认这些值会定期更新。

【讨论】:

  • 这个块实际上只包装了if (!PlayerPrefs.HasKey("then")) PlayerPrefs.SetString("then", getStringTime()); OP,它只是恶意
  • 啊,是的,你完全正确。我会删除那部分。
猜你喜欢
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2023-02-26
  • 2011-12-07
  • 1970-01-01
相关资源
最近更新 更多