在 C# unity 中,我的等待函数未正确等待

Lle*_*ell 6 c# unity-game-engine visual-studio

我最近学习了 C# unity 中的协程,并尝试创建一个等待函数来在代码之间等待。它同时打印两个语句,而不是等待三秒钟。有谁知道这个问题的解决方案?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Learninghowtoprogram : MonoBehaviour
{
    private void Start()
    {
        print("hello"); 
        wait(3);
        print("hello2");      
    }

    IEnumerator waito(float time)
    {
        yield return new WaitForSeconds(time);        
    }

    void wait(float time)
    {
        StartCoroutine(waito(time));     
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

这里的问题是当Start()被调用时它会尝试逐行执行

print("hello"); 
wait(3);
print("hello2");
Run Code Online (Sandbox Code Playgroud)

因此,当您调用它时,wait(3)它会进入它自己的作用域并调用waito协程。

现在看到它yield return new WaitForSeconds(time);正在正确地完成它的工作,这意味着它正在等待 3 秒,但在它的范围内(在其自身内部),所以你可以做的是像这样移动print("hello");print("hello2");在协程本身中..

public class Learninghowtoprogram : MonoBehaviour
{
    private void Start()
    {
        wait(3);
    }

    void wait(float time)
    {
        StartCoroutine(waito(time));
    }

    IEnumerator waito(float time)
    {
        print("hello");
        yield return new WaitForSeconds(time);
        print("hello2");
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您wait()也可以像这样删除并直接启动协程

public class Learninghowtoprogram : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(waito(3));
    }

    IEnumerator waito(float time)
    {
        print("hello");
        yield return new WaitForSeconds(time);
        print("hello2");
    }
}
Run Code Online (Sandbox Code Playgroud)