- Home /
Coroutine exits as soon as called
I have a coroutine that when called it instantly exits even before it gets to the first statement. The object that it is attached to does not get destroyed. The coroutine is called from a method that is then called from another script. The scripts movingTroops and navigate are on separate gameObjects.
Here is the script that has the coroutine in it:
public class navigate : MonoBehaviour
{
public void callMoveTo(Vector3 target)
{
StartCoroutine("MoveTo", target);
}
public IEnumerable MoveTo(Vector3 target)
{
while (Vector3.Distance(transform.position, target) > .5 && movingTroops.selectedUnits.Contains(gameObject))
{
//code
yield return 0;
}
}
Here is the script that calls the callMoveTo script:
public class movingTroops : MonoBehaviour {
public Vector3 target;
public static List<GameObject> selectedUnits = new List<GameObject>();
void Update () {
if (Input.GetMouseButtonDown(1))
{
RaycastHit position;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out position))
{
target = new Vector3();
target = position.point;
for (int i = 0; i < selectedUnits.Count; i++)
{
if (selectedUnits[i] != null)
{
GameObject navobject = selectedUnits[i];
var nav = navobject.GetComponent<navigate>();
nav.callMoveTo(target);
}
}
}
}
}
}
Answer by KpjComp · Oct 11, 2014 at 09:26 PM
Ah that helps, you have done -> IEnumerable instead of IEnumerator
Answer by gribbly · Oct 11, 2014 at 07:12 PM
You mean that your while condition isn't getting checked?
So if you did this you wouldn't see the log "TEST 1"?
public IEnumerable MoveTo(Vector3 target)
{
Debug.Log("TEST 1");
while (Vector3.Distance(transform.position, target) > .5 && movingTroops.selectedUnits.Contains(gameObject))
{
//code
yield return 0;
}
}
I doubt this is your problem, but noticed this:
var nav = navobject.GetComponent<navagate>();
...should be:
var nav = navobject.GetComponent<navigate>();
yes when I put a debug message there it doesn't show up. thanks for pointing out that typo.
So your coroutine is not being called at all.
$$anonymous$$ove the debug.log to the line before StartCoroutine and report back.
$$anonymous$$eep moving it up the chain if logic until you find the broken link or conditional
it all checks out the call$$anonymous$$oveTo is being called just fine. It's just the $$anonymous$$oveTo method that's not being called properly.
Does it work if you don't use a named Coroutine?. eg. StartCoroutine($$anonymous$$oveTo(target)); ins$$anonymous$$d? or maybe this.StartCoroutine()..