gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:19:06 24 4
gpt4 key购买 nike

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

代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com