Coroutine troubles

Hi,

I’m hoping someone can help me out with this problem. I’m trying to get my GameObject to move along a path, which is stored in an array. The GameObject moves along the path correctly but I’m trying to get the game to wait for the GameObject to finish moving before anything else can be done.

In addition, when I query the value of the busy variable after the line StartCoroutine(moveAlongPath()); busy returns as True, when it should be False. I understand that this is because of the nature of coroutines, they run alongside the current process, but I want to get the value of busy after the movement is complete. If I remove the coroutine of moveAlongPath unity crashes.

I’m using coroutines to smoothly move my GameObject.

Here’s the code. Thanks in advance.

#pragma strict

var busy: boolean = false;
var path: Array;

function moveLinear(goal: Vector3, rateOfMovement: float){

	var startPos: Vector3;
	
	while(true)
    {
    	busy = true;
		startPos = transform.position;
        
        if (startPos == goal)
        {
    		busy = false;
    		break;
    	}
    	
    	transform.position = Vector3.MoveTowards(startPos, goal, Time.deltaTime*rateOfMovement);
    	
        yield;
    }
}

function moveAlongPath () {

	var i: int = 0;
	
	while (i < path.length)
	{
		if (!busy)
		{
			Debug.Log(i);
			Debug.Log(busy);
			var goal: Vector3 = path*;*
  •  	StartCoroutine(moveLinear(Vector3(goal.x, 0, goal.z), 10));*
    
  •  	i++;*
    
  •  }*
    
  •  yield;*
    
  • }*
    }

function Start () {

  • path = new Array ();*
  • path = [Vector3(10,0,0),Vector3(20,20,0),Vector3(30,0,0),Vector3(40,40,0)];*
    }

function Update () {

  • if (Input.GetMouseButtonDown (0))*
  • {*
  •  StartCoroutine(moveAlongPath());*
    
  •  Debug.Log('b  '+busy);*
    
  • }*
    }

“In addition, when I query the value of the busy variable after the line StartCoroutine(moveAlongPath()); busy returns as True, when it should be False”

no, it should be TRUE.

if you YIELDED to moveLinear it would “wait” there, and on the next line it would be FALSE

But you are not yielding to it. You’re just telling it to run in the “background”. so it is imemdiately TRUE and stays TRUE for a few seconds or however long it will take to run.