Help with delayed loop?

I’m having a hard time with this script:

var myFloat : float[]; 

InvokeRepeating("MyLoop", 1, 13);

function MyLoop () {
	Debug.Log ("FIRE!");
	for (var value in myFloat) { 
		Debug.Log (value);
		yield new WaitForSeconds (2);
	} 
}

The problem seems to be in the “yield” command. What I want this to do is to start an infinite loop that will flip through the values of “myFloat” every 2 seconds and repeat the process every 13 seconds (there are 6 values for “myFloat” in the array). If I pull the “yield” command out it works, but there’s no delay. Can anyone help??

Thanks!

Hi BigKahuna,

Maybe you could do something like this:

var myFloat : float[];
private var curFloat : int;

InvokeRepeating("MyLoop", 1, 2);
InvokeRepeating("MyResetLoop", 1, 13);

function Start() {
	curFloat = myFloat.length;
}

function MyLoop () {
	Debug.Log ("FIRE!");

	if (curFloat < myFloat.length) {
      Debug.Log (myFloat[curFloat++]);
	}
}


function MyResetLoop () {
	Debug.Log ("RESET!");
	curFloat = 0;
}

Hope this helps,
Nathan

I don’t think you can use InvokeRepeating with coroutines; it only works with functions as far as I know.

–Eric

Why do any of that? Just put the for loop inside a while loop with the yield WaitForSeconds(1) at the end. It’s SOOOO much simpler to read and use.

while (true) {
   for (var value in myFloat) {
      Debug.Log (value);
      yield WaitForSeconds(2);
   }
   yield WaitForSeconds(1);
}

Of course, that’s if I understood that you wanted two seconds per value, and the entire thing to last thirteen seconds before repeating… I’m not completely sure what you’re trying to do.

The reason I am using InvokeRepeating() is because I want to be able to stop the loop (ie. with a CancelInvoke()). I tried using a while (true) {} loop but couldn’t figure out how to stop it. I tried adding a break command in the while loop, but couldn’t get it to work. (Part of my frustration is the lack of JavaScript documentation as it’s used in Unity.)

Couldn’t you just add an “Active” variable somewhere in there?

var isActive : bool;

while (true) {
   if ( isActive ) {
      for (var value in myFloat) {
         Debug.Log (value);
         yield WaitForSeconds(2);
      }
   }
   yield WaitForSeconds(1);
}

or:

var isActive : bool;

while (true) {
   for (var value in myFloat) {
      if ( isActive ) {
         Debug.Log (value);
         yield WaitForSeconds(2);
      }
   }
   yield WaitForSeconds(1);
}

You can do this with coroutines by invoking them with a string:

// First:
StartCoroutine("MyLoop");
// and later:
StopCoroutine("MyLoop");

function MyLoop() {
    while (true) {
        for (var value in myFloat) {
            Debug.Log("loop");
            yield WaitForSeconds(2);
        }
        yield WaitForSeconds(1);
    }
}

That’s what I was looking for! Thanks Adrian! Thanks everybody else, you’ve been extremely helpful!! :smile: