Clément Andraud
Clément Andraud

Reputation: 9269

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

I have multiple scripts like :

I have Start() end/or Awake() function in each. If I put a Debug.Log() in these functions I get something like (for have the order) :

It's ok for this order. Now I added in ItemDatabase a Coroutine for get Items from a database with WWW class, this is what I have :

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");
}

You can see differents Debug.Log(), and now If I check my console, I see this order :

My question is, why the end of Coroutine is after all Start() functions ? In my example, I need to ConstructItemDatabase() before Start : GalaxyGenerator.

Any ideas ?

Upvotes: 2

Views: 569

Answers (1)

Fredrik
Fredrik

Reputation: 5108

Because it takes some time to download your WWW. Your WWW-call doesn't have anything to do with the order of things, you're sending a request to a server and gets a response. If it's a big response it will take a lot of time, but either way it will take more time than it takes for Unity to go through your Awakes and Starts.

If you need the Start methods after the WWW is done, you should remove the code from Start() and put them in a method of your own, for instance InitializeInventory() and InitializeGalaxyGenerator() which you then call when your WWW is done, like you're doing with 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");
}

Upvotes: 3

Related Questions