InvokeRepeating and yield not good friends

Hi there,

I was codding when I encounter this possible error. The code is this:

function Start(){
InvokeRepeating("MyFunction", 1,10);
}

function MyFunction(){
print("hello");
yield WaitForSeconds(1);

}

This doesn’t print anything because the function isn’t been called correctly. If I delete the yield statement it works.

Any clue about this?

Is there any particular reason why you’d be doing that? It’s synonymous to sticking a hot metal shaft in your eye and wondering why it hurts.

I suspect it’s because yield can only be in coroutines that are started like coroutines, but an InvokeRepeating doesn’t start it like a coroutine.

You can’t use Invoke or InvokeRepeating with coroutines.

–Eric

Thx for the reply.

If we can’t use Inovoke or InvokeRepeating with coroutines this should appear in the documentation, if not how we realize that? Unity dosn’t throw any errors.

What Im trying to do is call a function each T time, and this function does things also time dependent. Like automatically activate a gun each 5 seconds, and on activation it fires 3 bullets with a time difference of 0.2 sec between bullets.

Thx again!

You could use a single looping coroutine for that:

function MyFunc()
{
while(!isDone)
{
//Do Something
yield WaitForSeconds(1);
}

}

This will perform an action every 1 second looping until you set isDone to true.

thx Ntero!

Thanks,I get it,too.

Weird, I just ran into this myself, and this seems to work!?

function Start () {
          InvokeRepeating("DoIt",0,2);	
}

function DoIt(){
	DoinStuff();
}

function DoinStuff(){
	print ("Doin' Stuff");
	
        var timer : float = 0.0;
	while (timer < 1){
		timer += Time.deltaTime;
		yield;
	}
	print ("Done");
}

Whereas going straight for DoinStuff from the invoke doesn’t work…