首页 > 解决方案 > 计数器未在统一 UI 上更新,但变量为

问题描述

在我正在开发的钓鱼迷你游戏中,玩家捕获的每条独特的鱼都被写入“日志”类型的 UI。如果玩家再次钓到了那种鱼,而不是在 UI 中写一个全新的条目,分数会增加 1 以显示他们钓到了多少次这种鱼。

我正在使用可编写脚本的对象来存储有关每条鱼的信息(名称、大小、图片等)以及它被捕获的次数。我可以在检查器中看到,每次捕获鱼时变量都会增加,并且每次捕获独特的鱼以及次数时,我都会调试一条消息。

UI 似乎会更新第一次捕获的次数,但是,每次捕获鱼后它似乎总是保持在 1,即使我正在写入 UI 的变量正在改变。

这是更新 UI 的代码:

public void UpdateFishPages(Fish fish)
{
    if (!CheckIfExists(fish))
    {
        Debug.Log("New Fish: " + fish.fishName + " " + "caught ");
        Debug.Log("Fish index: " + fishIndex);
        fishCaught.Add(fish);
        fishes[fishIndex].SetActive(true);
        fishes[fishIndex].GetComponent<Image>().sprite = fish.image;

        fishes[fishIndex].transform.GetChild(0).transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().text = fish.fishName;
        fishes[fishIndex].transform.GetChild(0).transform.GetChild(1).GetComponent<TMPro.TextMeshProUGUI>().text = fish.fishDesc;
        fishes[fishIndex].transform.GetChild(0).transform.GetChild(2).GetComponent<TMPro.TextMeshProUGUI>().text = fish.fishSize;

        string newFishCount = fish.timesCaught.ToString();
        Debug.Log(newFishCount);
        fishes[fishIndex].transform.GetChild(1).transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().text = newFishCount;
        fishIndex++;
    }
    else
    {   


        string newFishCount = fish.timesCaught.ToString();
        Debug.Log(fish.fishName + " now caught " + fish.timesCaught + " times!");

        fishes[fishIndex].transform.GetChild(1).transform.GetChild(0).GetComponent<TMPro.TextMeshProUGUI>().text = newFishCount;

    }
}

bool CheckIfExists(Fish fish)
{
    if (fishCaught.Contains(fish))
    {
        return true;
    }
    else
    {
        return false;
    }
}

下面是当玩家钓到鱼时我调用该方法的方式:

if (Input.GetKeyDown(KeyCode.E) || Input.GetButtonDown("Button A"))
            {
                if (timer < 1f)
                {
                    int randomFish = Random.Range(1, 5);
                    playerAnimator.SetInteger("fishing_randomIndex", randomFish);

                    fish[randomFish - 1].timesCaught++;

                    journal.UpdateFishPages(fish[randomFish - 1]);

                    //Debug.Log("caught");
                    timer = 0;
                    fishStage = 2;
                }
            }
            else if (timer > 1f)
            {
                //Debug.Log("Didn't reel");
                playerAnimator.SetTrigger("fishing_fail");

            }

我希望有人可以阐明我可能做错了什么。

非常感谢您的时间和帮助!

标签: c#unity3dscriptable-object

解决方案


推荐阅读