Unity与C#中布尔值仅单向生效?碰撞触发逻辑异常排查
问题:角色撞墙触发事件逻辑异常
我在实现角色撞墙触发事件的游戏逻辑时遇到问题——希望同一对象后续碰撞不再触发该事件,但第一段代码完全无法触发事件;仅切换布尔值counterOne的初始状态与判断逻辑的第二段代码却能正常工作,我原本预期两段代码功能一致。
无法生效的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CrashDetector : MonoBehaviour { [SerializeField] ParticleSystem finishEffect; [SerializeField] float delayTime = 5f; bool counterOne; private void OnTriggerEnter2D(Collider2D other) { if ((other.tag == "Respawn") && (counterOne)) { counterOne = false; FindObjectOfType<PlayerController>().DisableControls(); finishEffect.Play(); GetComponent<AudioSource>().Play(); Invoke("ReloadScene", delayTime); } } void ReloadScene() { SceneManager.LoadScene(0); } }
可正常生效的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CrashDetector : MonoBehaviour { [SerializeField] ParticleSystem finishEffect; [SerializeField] float delayTime = 5f; bool counterOne = false; private void OnTriggerEnter2D(Collider2D other) { if ((other.tag == "Respawn") && (!counterOne)) { counterOne = true; FindObjectOfType<PlayerController>().DisableControls(); finishEffect.Play(); GetComponent<AudioSource>().Play(); Invoke("ReloadScene", delayTime); } } void ReloadScene() { SceneManager.LoadScene(0); } }
问题原因分析
两段代码的核心差异在于布尔变量的初始值与判断逻辑的匹配:
- 在C#的Unity环境中,类的成员布尔变量默认初始值为
false。第一段代码里bool counterOne;没有显式赋值,默认是false,而判断条件要求counterOne为true才能进入分支,所以第一次碰撞时条件永远不满足,事件完全无法触发。 - 第二段代码显式将
counterOne初始化为false,判断条件用!counterOne(即取反),第一次碰撞时条件成立,执行完逻辑后将counterOne设为true,后续碰撞时条件不满足,刚好实现了“同一对象仅触发一次事件”的需求。
内容的提问来源于stack exchange,提问作者Max Henry
相关产品推荐
相关产品推荐

