Unity:为什么协程在所有 Start() 函数之后结束?

Unity : Why coroutine end after all Start() functions?

我有多个脚本,例如:

我每个都有 Start() end/or Awake() 函数。如果我在这些函数中放置一个 Debug.Log() 我会得到类似的东西(有订单):

这个订单没问题。现在我在 ItemDatabase 中添加了一个协程,用于使用 WWW class 从数据库中获取项目,这就是我所拥有的:

void Awake(){
    Debug.Log("Awake : ItemDatabase");
    StartCoroutine(DoWWW());
}

private IEnumerator DoWWW()
{
    Debug.Log("Before www");
    www = new WWW("http://127.0.0.1:8000/api/items");
    yield return www;

    Debug.Log("After www");

    itemData = JsonMapper.ToObject (www.text);
    ConstructItemDatabase();
}

void ConstructItemDatabase()
{
    Debug.Log("Construct ItemDatabase");
}

你可以看到不同之处 Debug.Log(),现在如果我检查我的控制台,我会看到这个顺序:

我的问题是,为什么协程的结尾毕竟是Start()函数?在我的示例中,我需要在 Start : GalaxyGenerator.

之前 ConstructItemDatabase()

有什么想法吗?

因为下载您的 WWW 需要一些时间。您的 WWW 调用与事物的顺序没有任何关系,您正在向服务器发送请求并获得响应。如果响应很大,则需要花费很多时间,但无论哪种方式,它所花费的时间都将超过 Unity 完成唤醒和开始所需的时间。

如果你在WWW完成后需要Start方法,你应该从Start()中删除代码并将它们放在你自己的方法中,例如InitializeInventory()InitializeGalaxyGenerator()然后你在 WWW 完成后调用,就像你正在使用 ConstructItemDatabase 一样。

private IEnumerator DoWWW()
{
    Debug.Log("Before www");
    www = new WWW("http://127.0.0.1:8000/api/items");
    yield return www;

    Debug.Log("After www");

    itemData = JsonMapper.ToObject (www.text);
    ConstructItemDatabase();
    InitializeInventory();
    InitializeGalaxyGenerator();
}

void ConstructItemDatabase()
{
    Debug.Log("Construct ItemDatabase");
}