首页 > 解决方案 > Unity c#使用其他脚本中的变量不起作用

问题描述

我尝试编写一个小游戏。我的问题:我有一个跳转计数器,它的名字是什么。我想在面板中显示这个数量的跳跃,如果我与“目标”发生碰撞,就会出现。但是,如果我发生碰撞,并且面板出现,则只有: Jumps required: 0 并且我得到以下错误代码:

NullReferenceException:对象引用未设置为对象 GameScript.Start () 的实例(在 Assets/Scripts/GameScript.cs:28)

最大的问题是,变量不在另一个脚本中,jumpcounter 自己工作正常

我做了 YouTube 上很多视频所说的,所以检查我是否真的将 UI 文本附加到我的公共文本,但我没有看到任何视频具有真正有用的答案......

private void Start()
{
    counter = Player.GetComponent<PlayerController>().jumpCounter;
}

private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.name == "Hand")
    {
        LevelFinishedPanel.SetActive(true);
        Player.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;

        if (counter <= maxJumpsForGold)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Gold.enabled = true;
        }
        else if (counter <= maxJumpsForSilver && counter > maxJumpsForGold)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Silver.enabled = true;
        }
        else if (counter <= maxJumpsForBronze && counter > maxJumpsForSilver)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Bronze.enabled = true;
        }
        else
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
        }

我希望显示我的跳跃量,但实际上它只是 0。

标签: c#unity3d

解决方案


counter在 Start() 处设置变量,但在其他脚本中更新变量时它不会更新。发生这种情况是因为即使您在 Start() 将其设置为 player 上的 jumpCounter 的值,它也不会“绑定”到该值。您实际上只是创建另一个具有 jumpCounter 值的变量。请尝试以下操作:

private void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.name == "Hand")
    {
        counter = Player.GetComponent<PlayerController>().jumpCounter;
        LevelFinishedPanel.SetActive(true);
        Player.GetComponent<Rigidbody2D>().constraints = 
RigidbodyConstraints2D.FreezeAll;

        if(counter <= maxJumpsForGold)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Gold.enabled = true;
        }
        else if (counter <= maxJumpsForSilver && counter > maxJumpsForGold)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Silver.enabled = true;
        }
        else if (counter <= maxJumpsForBronze && counter> maxJumpsForSilver)
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
            Bronze.enabled = true;
        }
        else
        {
            ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();

        }
    }
}

在这里,不是在 Start() 处设置它,而是在发生碰撞时设置变量。


推荐阅读