检测到触发器时添加UI文本



检测到触发器时如何添加UI文本?我有此代码可以检测播放器是否在触发器中或之外,但是如果播放器进出触发器,我想在画布中出现一条消息,并在画布中出现一条消息。谢谢!

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);
}
}

只需在您的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中只需将引用添加到文本组件中。

最新更新