首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使ui文本在5秒后出现在场景中,并使ui文本在8秒后消失unity3d

问如何使ui文本在5秒后出现在场景中,并使ui文本在8秒后消失unity3d
EN

Stack Overflow用户
提问于 2016-09-06 04:07:36
回答 1查看 681关注 0票数 0

我有一些问题。我需要UI文本在场景中显示至少6秒后,并在8秒后消失。下面是我的代码:

代码语言:javascript
复制
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 = "";
 }
}  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-06 07:31:29

您没有在任何地方定义文本,也没有使用using UnityEngine.UI;导入UI命名空间。现在,如果您想在计数时查看时间,可以使用timeShown += Time.deltaTime;代码。

如果您想要做的只是等待几秒钟,那么只需使用yield return new WaitForSecondsRealtime(timeValue);或yield return new WaitForSeconds(timeValue);

代码语言:javascript
复制
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秒,然后隐藏文本,这就是上面的例子应该做的。尽管这对我来说没什么意义。您很可能希望使用第二个参数来指定在隐藏文本之前等待多长时间。如果是这种情况,请执行以下操作:

代码语言:javascript
复制
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));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39337073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档