c# - 如何检测触发器中的对象?

标签 c# unity3d

我在场景中放置了一个带有触发器的对象,我希望控制台在我单击按钮时向我发送一条消息,检测玩家是在触发器内还是在触发器外。当我玩游戏时,它只会在玩家进入触发器时向我发送一条消息。

代码:

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

public class MapDetect : MonoBehaviour {


     void OnTriggerStay(Collider other)
     {
         if (other.gameObject.tag == "Player") {
             Debug.Log ("Map ON");

         } 
         else {
             if (other.gameObject.tag == "Player") {
                  Debug.Log ("Map OFF");
             }
         }
     }
}

最佳答案

使用 OnTriggerEnterOnTriggerExit 而不是 OnTriggerStay 来保持当前状态:

public class MapDetect : MonoBehaviour {

    private bool isTriggered;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
            isTriggered = true;
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
            isTriggered = false;
    }

    void Update(){
        if(Input.GetKey(KeyCode.Space)){
            Debug.Log(isTriggered);
        }
    }
}

关于c# - 如何检测触发器中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42627581/

相关文章:

c# - 如何从 Unity Android 应用程序打开 Android 系统设置

c# - 是否可以一起使用 DDD 和 BDD?

c# - 预加载 WPF DataGrid

c# - 发生异常时关闭数据库连接的正确方法

c# - 四元数反向旋转?

c# - 如何解决 "' UnityEngine.Random' does not contain a definition for 'Next' ...”错误?

c# - LINQ左外连接查询错误: OuterApply did not have the appropriate keys

c# - C#中字符串转int并测试成功

c# - Unity Error building Player 因为脚本有编译器错误

c# - Unity 5.3.5f1在播放模式下崩溃