C# 当我尝试每10秒向屏幕显示一次文本时,它永远不会起作用
我正在尝试使用TextMeshPro每10秒启用一条文字,上面写着“升级”,游戏正在运行,但我一直在搜索,找不到任何有助于解决此问题的内容。我也看到过使用InvokeRepeating方法的代码,但从我尝试的代码来看,它也不起作用 代码如下:C# 当我尝试每10秒向屏幕显示一次文本时,它永远不会起作用,c#,unity3d,C#,Unity3d,我正在尝试使用TextMeshPro每10秒启用一条文字,上面写着“升级”,游戏正在运行,但我一直在搜索,找不到任何有助于解决此问题的内容。我也看到过使用InvokeRepeating方法的代码,但从我尝试的代码来看,它也不起作用 代码如下: using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class LevelUp : MonoBehaviour
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LevelUp : MonoBehaviour
{
public TextMeshProUGUI LevelUpText;
public int NumberOfSeconds;
void Update() {
if(Time.time % 10 == 0 && Time.time != 0) {
StartCoroutine(EnableText());
}
}
public IEnumerator EnableText() {
LevelUpText.enabled = true;
yield return new WaitForSeconds(NumberOfSeconds);
LevelUpText.enabled = false;
}
}
时间很可能永远不会被10整除。因为每一帧都调用Update,所以您可能会在t=9.6时得到更新,然后在t=10.1时得到下一帧 使用协同程序,您可以创建一个无限循环,如下所示
void Start() {
StartCoroutine(TextRoutine());
}
public IEnumerator TextRoutine() {
while(true) {
LevelUpText.enabled = true;
yield return new WaitForSeconds(BlinkDelaySeconds);
LevelUpText.enabled = false;
yield return new WaitForSeconds(LevelUpDelaySeconds);
}
}
如果要使用InvokeRepeating,则必须创建一个启动协同路由的函数(而不是直接作为函数调用协同路由)
为什么不简单地对这两种延迟使用协同程序,即有文本和无文本的时间,而不是
更新?
void Start() {
InvokeRepeating("EnableText", NumberOfSeconds, 0f);
}
void EnableText() {
StartCoroutine(EnableTextRoutine());
}
IEnumerator EnableTextRoutine() ...