# Coroutine only partially executing

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.

1. EnemyHandler.cs

public class EnemyHandler : MonoBehaviour
{
public int mob_id;
{
Debug.Log("Checkpoint 1");

WWWForm form = new WWWForm();
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 variables are set here
Debug.Log("@@@@@@ Checkpoint 3 @@@@@@");
break;

default:
Debug.Log("Error!");
break;
}

}

{
mob_id = requested_mob_id;
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()
{
}
}


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.

• Please post your solution as an Answer, not embedded in the question itself. – DMGregory Nov 14 '19 at 12:21
• Wasn't sure if I was right. I'll take that to mean that I am, then. Thank you! @DMGregory – Sainath Krishnan Nov 14 '19 at 14:46
• If the solution works, it works. I don't have any insight for you at the moment about why this would work differently than what you had before. – DMGregory Nov 14 '19 at 15:51

I have fixed this by turning the function I use to initialize the Coroutine into an IEnumerator, and adding a yield return to the call.
(The same effect can be achieved by changing Start from void to IEnumerator, if the Coroutine is initialized in Start).