c# - 尝试检查另一个脚本中的布尔值是否为真
问题描述
我正在尝试在 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) {...}
并没有改变错误。
解决方案
你不应该在你已经获得的对象上寻找另一个LeperTrigger
组件。我更改了下面的第 17 行。LeperTrigger
Start()
如果您仍然遇到相同的错误,请务必检查:
- 您确实在场景中有一个带有标签的对象
enemy
- 带有标签的对象附有
enemy
一个LeperTrigger
脚本。
最后,如果在场景开始后enemy
实例化对象,请记住 的方法不会再次运行,从而使对象为空。Start()
LeperAI
lepertriggerinstance
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");
}
}
}
推荐阅读
- c# - Xamarin Forms CollectionView 绑定后保持为空
- java - 在复合键上使用“链式”外键时出现问题
- python - 过滤 Div,BeautifulSoup,带空返回
- android - 从与帐户触发器关联的联系人的意图中提取联系人信息
- php - 新的 WP_REST_Request(PUT)
- python - 尝试 MNIST 数据集时出现 tensorflow 和 matplotlib 包的问题
- protocol-buffers - .Net Framework/C# - --grpc_out:protoc-gen-grpc:访问被拒绝问题
- php - Symfony 5 缓存:清除 php.CRITICAL:致命错误:允许的内存大小
- bash - 将 JSON 传递给 aws secretsmanager 时转义字符
- html - 如何使用css围绕文本创建一个圆圈?