如何在检测到触发器时添加UI文本? 我有这个代码来检测玩家是否进入或不在触发器中我想在画布中显示一条消息,如果玩家进入/退出触发器,则“Map on”/“Map off”。谢谢!
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);
}
}
}
更新代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DetectarMapa : MonoBehaviour {
public GameObject T1;
public GameObject T2;
public float time = 3;
void Start ()
{
T1.SetActive (true);
StartCoroutine(Message1());
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
T2.SetActive (true);
StartCoroutine(Message2());
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
T1.SetActive (true);
StartCoroutine(Message1());
}
IEnumerator Message1 ()
{
yield return new WaitForSeconds(time);
T1.SetActive (false);
}
IEnumerator Message2 ()
{
yield return new WaitForSeconds(time);
T2.SetActive (false);
}
}
答案 0 :(得分:1)
只需添加对Text
组件的引用,并在需要时设置text
属性:
public class MapDetect : MonoBehaviour {
public Text Text;
void Start()
{
Text.text = "Map out";
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
Text.text = "Map on";
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
Text.text = "Map out";
}
}
然后在Unity中添加对Text组件的引用。