Can't get a coroutine to work as expected.

Hi, I’m having trouble with this coroutine. Basically all I want is for my enemy to wait for 3 seconds before moving each time it moves. At present the enemy waits for 3 seconds and then it stops working. The only thing I can think of is that the wait gets called every frame so that after the first wait you can’t ‘see’ it waiting anymore. Anyway, here’s the code:

void FixedUpdate(){


		StartCoroutine (directionGetter ());

	
	}

	IEnumerator directionGetter(){
		while (true) {
						yield return new WaitForSeconds (3f);
						directionChange = Random.Range (1, 5);
						if (directionChange == 1) {

								myTransform.Translate (Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
								
						}

						if (directionChange == 2) {
			
								myTransform.Translate (-Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
								
						}
	
						if (directionChange == 3) {
			
								myTransform.Translate (Vector3.right * enemySpeed * enemyHealth * Time.deltaTime);
								
						}
	
						if (directionChange == 4) {
			
								myTransform.Translate (-Vector3.right * enemySpeed * enemyHealth * Time.deltaTime);
								
						}

Thanks in advance for any help :slight_smile:

Create a bool system for checking if the coroutine is running. In fixed update put this:

bool inRoutine = false;

void FixedUpdate()
{

if( !inRoutine )
{

inRoutine = true
StartCoroutine( DirectionGetter());
}
}

IEnumerator DirectionGetter()
{

while( inRoutine )
{

yield return new WaitForSeconds (3);
directionChange = Random.Range( 1, 5 );

if( directionChange == 1 )
{

myTransform.Translate(Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
}

//your other code...

There is nothing to stop it working in what you’ve shown

IEnumerator directionGetter(){
   while(true){
      yield return new WaitForSeconds(3f);
      //do

   }
}

This will keep repeating every three seconds as you’d expect, just make sure you don’t have a break or another return somewhere down the bottom of what you’ve pasted.

Also take a look at the switch statement instead of using multiple ifs, rules of thumb if you’re using more than three ifs use a switch, if you’re using three or less use “else if”. Currently your code is checking every directionChange even though it’s known to only ever be one.