当我尝试每10秒在屏幕上显示一次文本时,它永远不会起作用



我正在尝试启用一个文本,该文本表示";LEVEL UP";使用TextMeshPro,游戏每10秒运行一次,但我一直在搜索,找不到任何有助于解决这个问题的东西。我还看到了具有InvokeRepeating方法的代码,但从我尝试的情况来看,它也不起作用。

这是代码:

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

Time.Time很可能永远不会被10整除。由于"更新"是在每帧调用的,因此您可能会在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() ...

最新更新