unity3d 如何每隔X秒调用一次协程?

o8x7eapl  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(301)

我试图使一个类有一个协程运行每2秒。如果它的工作,它应该打印到控制台“Ran”每2秒。然而,目前的版本只是打印到控制台似乎每一帧。这怎么能在逻辑上修复?

public class EveryXSeconds: MonoBehaviour
{

    public bool running = true;

    private void Update()
    {
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        // Set the function as running
        running = true;

        // Do the job until running is set to false
        while (running)
        {
            // Do your code
            print("Ran");

            // wait for seconds
            yield return new WaitForSeconds(2f);
            running = false;
        }
    }
}
xwbd5t1u

xwbd5t1u1#

public class EveryXSeconds: MonoBehaviour{

    private void Start()
    {
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        while (true)
        {
            // Do your code
            print("Ran");

            // wait for seconds
            yield return new WaitForSeconds(2f);
        }
    }
}

如果您填写以上内容,则每2秒打印一次。

相关问题