I have a Coroutine that I use to pull and spawn an enemy in my game. This coroutine works perfectly fine, with the exception of the very first call. I am fairly certain this is because I am probably loading something before it is ready, but I don't know enough to know where.
This is my code (Note the Debug.Log entries). I have removed whatever I think is irrelevant code.
EnemyHandler.cs
public class EnemyHandler : MonoBehaviour { public int mob_id; IEnumerator LoadMob() { Debug.Log("Checkpoint 1"); WWWForm form = new WWWForm(); form.AddField("mob_id",mob_id); WWW www = new WWW("my-url-here",form); yield return www; Debug.Log("@@@@@@ Checkpoint 2 @@@@@@"); string[] webResults = www.text.Split('\t'); int returncode = int.Parse(webResults[0]); switch (returncode) { case 0: //Mob Loaded Successfully //Mob variables are set here Debug.Log("@@@@@@ Checkpoint 3 @@@@@@"); break; default: Debug.Log("Error!"); break; } } public void CallMobLoad(int requested_mob_id) { mob_id = requested_mob_id; StartCoroutine(LoadMob()); Debug.Log("Coroutine called! Checkpoint 0"); } }
2.GameManager.cs (This is my primary class)
public class GameManager : MonoBehaviour
{
public GameObject spawnManager;
public static EnemyHandler thisenemy;
void Start()
{
thisenemy = spawnManager.AddComponent<EnemyHandler>();
thisenemy.CallMobLoad(1);
}
}
CallMobLoad is called once at Start, and every time a monster dies. It never works when called in Start(), but always works after that.
Furthermore, the first call only calls the first 2 Debug.Logs "Checkpoint 0" and "Checkpoint 1", none of the other checkpoints are hit. Every subsequent call works correctly and hits all checkpoints.
I really want to learn how/why this happens, Any help is greatly appreciated!
EDIT: I have fixed this by turning Start into an IEnumerator, and adding a yield return
to thisenemy.CallMobLoad(mobloadtemp);
Still not sure if this is the best way to do this, so please do advise.