首页 > 解决方案 > 尝试检查另一个脚本中的布尔值是否为真

问题描述

我正在尝试在 Unity 中编写游戏。我的计划是编写一个脚本,当玩家与对象碰撞时,使布尔变量为真,然后,另一个脚本将每次检查布尔变量是否为真。如果是真的,我会打印“Leper Jump”。由于 bool 变量在另一个脚本中,我需要对其进行实例化,并且代码看起来完全正确,但控制台在第 17 行显示“NullReferenceException:对象引用未设置为对象的实例”。抱歉,如果这听起来是个愚蠢的问题,但我已经尝试解决这个问题几个小时了,但我还没有找到解决方案,你能帮我吗?

这是我将播放器碰撞的布尔值转换为真值的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeperTrigger : MonoBehaviour
{
    public GameObject Leper;
    public GameObject trigger;
    public bool IsOnLeper = false;

    void Update()
    {

    }

     private void OnCollisionEnter2D(Collision2D collision)
         {
                if (collision.gameObject.tag == "Player")
                {
                Debug.Log("IsOnLeper comes true");
                IsOnLeper = true;
                }
        }
}

这是我尝试检查 bool 是否为真的脚本(错误在这里):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeperAI : MonoBehaviour
{

    public LeperTrigger lepertriggerinstance;

    void Start()
    {
        lepertriggerinstance = GameObject.FindWithTag("enemy").GetComponent<LeperTrigger>();
    }

    void Update()
    {
        if(lepertriggerinstance.GetComponent<LeperTrigger>().IsOnLeper == true)
        {
            Debug.Log("Leper jump");
        }
    }
}

错误是:NullReferenceException: Object reference not set to an instance of an object (line 17)

使用if (lepertriggerinstance.IsOnLeper) {...} 并没有改变错误。

标签: c#unity3d

解决方案


你不应该在你已经获得的对象上寻找另一个LeperTrigger组件。我更改了下面的第 17 行。LeperTriggerStart()

如果您仍然遇到相同的错误,请务必检查:

  • 您确实在场景中有一个带有标签的对象enemy
  • 带有标签的对象附有enemy一个LeperTrigger脚本。

最后,如果在场景开始enemy实例化对象,请记住 的方法不会再次运行,从而使对象为空。Start()LeperAIlepertriggerinstance

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeperAI : MonoBehaviour
{

    public LeperTrigger lepertriggerinstance;

    void Start()
    {
        lepertriggerinstance = GameObject.FindWithTag("enemy").GetComponent<LeperTrigger>();
    }

    void Update()
    {
        if(lepertriggerinstance.IsOnLeper == true)
        {
            Debug.Log("Leper jump");
        }
    }
}

推荐阅读