WaitForSeconds with InvokeRepeating

Hi!

This is probably a very basic question that has been tackled before, though I couldn’t seem to find an answer in other threads.

I’m trying to instantiate an object according to a certain rhythm that repeats every 4 seconds:

var beat : Rigidbody;

InvokeRepeating ("BeatMaker",3,4);

function BeatMaker(){
instance = Instantiate(beat,Vector.zero,Quaternion.identity);
instance.velocity = Vector3.up;
//yield WaitForSeconds(0.5);
//instance = Instantiate(beat);
//instance.velocity = Vector3.up;
}

The above code works, but when I add the commented (//)lines I get zilch.

I’m just trying to get to grips with various timing and rhythm techniques, and I’d be grateful for any pointers.

cheers!
Thom

I guess it’s because with invoke all the lines are evaluated instantaneously.

I managed to get the desired effect using a coroutine with a while(true) loop, but I get a drift in the timing this way.

The reason is that any function with a yield in it becomes a Coroutine. Coroutines cannot work with every Unity feature. For instance, Update and OnGUI cannot be Coroutines. Functions that are called through InvokeRepeating are another such exception.

The solution is simple, just call another function that contains the yield code and call that one from your InvokeRepeating function:

var beat : Rigidbody; 

function Start()
{
    InvokeRepeating ("BeatMaker",3,4);
}

function BeatMaker()
{
 
    RealBeat();
}

function RealBeat()
{
    instance = Instantiate(beat,Vector.zero,Quaternion.identity);
    instance.velocity = Vector3.up;
    yield WaitForSeconds(0.5);
    instance = Instantiate(beat);
    instance.velocity = Vector3.up;
}

Note that I also moved your InvokeRepeating call into a start function, as having code outside functions can lead to all sorts of unexpected bugs.

That makes a lot of sense - thanks a lot!

best,

Thom