Unity中引用其他游戏对象Bool值失效?求助排查
问题根源:赋值与比较运算符混淆
你的代码核心错误是在if条件中误用了赋值运算符=,而非比较运算符==:
isPoor = true:这是将isPoor强制设为true的赋值操作,该表达式的返回值也是true,因此第一个if语句永远会执行,导致无论哪种预制体进入碰撞盒都会触发游戏失败。isPoor = false:同理,这是将isPoor设为false的赋值操作,表达式返回值为false,第二个if永远不会被触发。
修正后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class accept : MonoBehaviour { public LayerMask grabbable; public GameObject Spawner; bool isPoor; public GameManager gameManager; public void OnTriggerEnter2D(Collider2D other) { // 先获取组件并做空引用判断,避免报错 Poor poorComponent = other.gameObject.GetComponent<Poor>(); if (poorComponent == null) { Debug.LogWarning("进入碰撞盒的物体未挂载Poor组件!"); Destroy(other.gameObject); Spawner.GetComponent<Spawner>().Spawn(); return; } isPoor = poorComponent.isPoor; // 直接用布尔值判断,替代冗余的比较写法 if (isPoor) { gameManager.GameOver(); } else { gameManager.GameWon(); } Destroy(other.gameObject); Spawner.GetComponent<Spawner>().Spawn(); } }
额外优化建议
- 布尔值判断无需写
isPoor == true,直接用if(isPoor)更简洁易读,else自然对应isPoor == false的场景。 - 增加
Poor组件的空引用判断,能避免非目标物体进入碰撞盒时引发报错,方便调试。 - 遵循C#命名规范,建议将类名
accept改为Accept,提升代码可读性。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

