我有一些问题。我需要UI文本在场景中显示至少6秒后,并在8秒后消失。下面是我的代码:
using UnityEngine;
using System.Collections;
public class ssj : MonoBehaviour {
IEnumerator ShowMessageCoroutine(string message, float timeToShow = 10)
{
// Show the text
text.text = message;
// Wait for 10 seconds
float timeShown = 0f;
while (timeShown < timeToShow)
{
timeShown += Time.deltaTime;
yield return null;
}
// Hide the text
text.text = "";
}
} 发布于 2016-09-06 07:31:29
您没有在任何地方定义文本,也没有使用using UnityEngine.UI;导入UI命名空间。现在,如果您想在计数时查看时间,可以使用timeShown += Time.deltaTime;代码。
如果您想要做的只是等待几秒钟,那么只需使用yield return new WaitForSecondsRealtime(timeValue);或yield return new WaitForSeconds(timeValue);
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ssj : MonoBehaviour {
public Text text;
IEnumerator ShowMessageCoroutine(string message, float timeToShow = 10)
{
//Wait for 5 seconds
yield return new WaitForSecondsRealtime(5f);
// Show the text
text.enabled = true;
text.text = message;
//Wait for 8 seconds
yield return new WaitForSecondsRealtime(8f);
// Hide the text
text.enabled = false;
text.text = "";
}
}确保将文本拖到脚本中的文本槽中
标题说你想等待5秒,显示文本,再等待8秒,然后隐藏文本,这就是上面的例子应该做的。尽管这对我来说没什么意义。您很可能希望使用第二个参数来指定在隐藏文本之前等待多长时间。如果是这种情况,请执行以下操作:
public Text text;
IEnumerator ShowMessageCoroutine(string message, float timeToShow = 10)
{
// Show the text
text.enabled = true;
text.text = message;
//Wait for specified seconds (timeToShow)
yield return new WaitForSecondsRealtime(timeToShow);
// Hide the text
text.enabled = false;
text.text = "";
}调用函数:StartCoroutine(ShowMessageCoroutine("Hello", 8));
https://stackoverflow.com/questions/39337073
复制相似问题