当前位置: 首页 > 编程语言 > C#

如何检测触发器中的对象?分享

时间:2023-04-10 12:36:49 C#

如何检测触发器中的对象?我在场景中放置了一个带有触发器的对象,我希望控制台向我发送一条消息,以在我单击按钮时检测玩家是否在触发器中。当我玩游戏时,它只会在玩家进入触发器时向我发送消息。代码:使用System.Collections;使用System.Collections.Generic;使用统一引擎;publicclassMapDetect:MonoBehaviour{voidOnTriggerStay(Colliderother){if(other.gameObject.tag=="Player"){Debug.Log("MapON");}else{if(other.gameObject.tag=="Player"){Debug.Log("MapOFF");}}}}使用OnTriggerEnter和OnTriggerExit而不是OnTriggerStay来保持当前状态:publicclassMapDetect:MonoBehaviour{privateboolisTriggered;voidOnTriggerEnter(Colliderother){if(other.gameObject.CompareTag("Player"))isTriggered=true;}voidOnTriggerExit(Colliderother){if(other.gameObject.CompareTag("Player"))isTriggered=false;}voidUpdate(){if(Input.GetKey(KeyCode.Space)){Debug.Log(isTriggered);}}}你的逻辑是完全错误的。您只是在检查TRIGGER是否在您的绑定中,但仍在尝试记录“MapOFF”消息,这永远不会发生。使用OnTriggerEnter和OnTriggerExit代替OnTriggerStar方法。然后仅在需要时(或在调试模式下)打印消息:}}voidOnTriggerExit(Colliderother){if(other.gameObject.CompareTag("Player")){m_IsPlayerOnTheMap=false;}}voidUpdate(){#ifDEBUGif(m_IsPlayerOnTheMap){Debug.Log("MapON");}else{Debug.Log("地图关闭");}#endif}privateboolm_IsPlayerOnTheMap=false;尝试:使用System.Collections;使用System.Collections.Generic;使用统一引擎;公共类MapDetect:MonoBehaviour{voidOnTriggerEnter(Colliderother){if(other.gameObject.CompareTag("Player")){Debug.Log("MapON");}}voidOnTriggerExit(Colliderother){if(other.gameObject.CompareTag("Player")){Debug.Log("MapOFF");}}}它在你进入时打开,在你退出时关闭(现在它只打印结果)。希望能帮到你。以上是C#学习教程:Howtodetectobjectsintriggers?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: