Startcoroutine 不工作

Startcoroutine is not working

我正在尝试延迟显示两个文本。但它不起作用。 代码是:

public class Class1: MonoBehaviour 
{
    public Text text1, text2;
    public bool inArea = false;

    private void Update () 
    {
       if (!inArea)
       {
           inArea     = true;
           text1.text = "";
           text2.text = "text2";
           StartCoroutine(timer());
           text2.text = "text3";            
      }
 }
 IEnumerator timer()
 {
     yield return new WaitForSeconds(100);
 }

我也试过了WaitForSecondsRealTime()。它也不起作用。

我觉得你有点误解了。

协程将运行与其他东西并行(在你的情况下是text2.text = "text3")如果它本身没有延迟yield(为此你需要调用你的来自协程的协程或使用 javascript 这将在内部执行此操作)。

您要么必须将所有代码移动到应该受延迟影响的协程,如下所示:

private void Update () 
{
    if (!inArea)
    {
        inArea = true;
        StartCoroutine(timer());          
    }
}

IEnumerator timer()
{
    text1.text = "";
    text2.text = "text2";

    yield return new WaitForSeconds(100);
    text2.text = "text3";  
}

或者您也可以通过将 void Update 更改为 IEnumerator Update 来使 Update 成为协程。

在你目前的情况下,第一个应该没问题。