2017-03-06 27 views
1

如何在检测到触发时添加UI文本? 我有这段代码来检测玩家是否在触发器中,但是如果玩家进出触发器,我希望在画布上出现一个消息“Map on”/“Map off”。谢谢!检测到触发时添加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); 
} 
} 
+1

你甚至没有尝试过。你不能实现点击按钮[part](http://stackoverflow.com/q/42632196/3785314)?这是很好的问和得到答案,但也很好,以表明你已经尝试了一些。否则,你希望人们从头到尾编写你的游戏脚本。 – Programmer

+0

对不起!现在,我没有时间来实现点击按钮部分。当我尝试它时,我会写在这里。 – Angelsm

回答

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

然后简单的引用添加到文本组件。

+0

当玩家进入触发器时,文本出现,但是当他没有出现时 – Angelsm

+0

我已经检查玩家何时进入或退出触发器的消息出现,但是如果他从触发器开始没有出现消息。我该如何解决? – Angelsm

+0

@Angelsm我不明白你的问题。你的意思是'OnTriggerExit'方法永远不会被调用? –