首页 > 解决方案 > Unity 像线程一样使用协程?

问题描述

我有一个耗时的功能,例如...

Debug.Log("A");

void Froze_Function() {
  for(int i=0; i<50000; ++i)
    // take some time...

  Debug.Log("B");
}

Debug.Log("C");

我不希望“Froze_Function”延迟我的统一程序,所以我希望它在其他线程中运行。

Unity有一个协程,但我不知道如何正确地使用协程来制作这个功能。

请不要说优化我的功能...

标签: unity3dcoroutine

解决方案


void Start()
{
    Debug.Log("A");
    StartCoroutine(Froze_Function());
    Debug.Log("C");
}

//Inside a method (class should be MonoBehavour) call: StartCoroutine(Froze_Function()); 

IEnumerator Froze_Function()
{
    float dist;
    for (int i = 0; i < 500; ++i)
    {
        dist = Vector3.Distance(Vector3.up, Vector3.left);
        yield return 0;
    }

        Debug.Log("B");
    yield return 0;
}

推荐阅读