triggering a function every x seconds

Well it’s basically the title :stuck_out_tongue: .

I’d like to trigger a function consistently every x amount of seconds.

Any ideas?

Check out Coroutines: http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html

so basically, you want something like this:

var x = 2.0;// amount of seconds between iterations

function Do ()
{
    exitCondition = false;
    do{
        //do stuff here
   
        yield WaitForSeconds (x);
    } while (!exitCondition);
}

function Start ()
{
    Do ();
}

When I put something where you said to put code, it says I need to replace my “;” with “:” .

Occurs here :

function Do () 
{ 
    exitCondition = false; 
    do; { 
    
    BroadcastMessage ("Decrease");

    
    yield WaitForSeconds (x); 
    
    } while (!exitCondition); 
}

InvokeRepeating is easier.

–Eric

var x = 2.0;// amount of seconds between iterations

function Do ()
{
   while(true){
   //DoStuffHere;
print("Doing Stuff"+ Time.time);
        yield WaitForSeconds (x);
    }
}

function Start ()
{
    Do ();
}

Cheers Aaron- works like a charm :smile: !

Just remember if you remove the yield line, it will cause an infinte loop, which will lock up unity and you’ll be force quitting. you can have

yield;

or

yield WaitForSeconds(x);

but neither and you’ll be swearing a little, or a lot depending on when you saved last!

Glad to help

Aaron

just to clarify, this throws error because of the ; after your do.

Is InvokeRepeating frame rate independent? ie. more accurate than running a script in update like…

current_time = Time.time;

if (current_time >= next_time) {
next_time = current_time + 0.3;
// DoSomething();
}

Just curious if anyone knows. thx

It wouldn’t be any more accurate since it runs in the same thread as the rest, but it’s simpler and easier to use.

–Eric

haha, cool. I got all excited for like 0.3 seconds there! It would have saved me at least a handful of lines of code. I just discovered Coroutines… amazing helpful stuff.

The callback timer was a key thing in Flash programming and now I know where to find it. Awesome.

does anyone know when I would run this script, if I change the value of x to anything but 2 it destroys my GameObject.

All I am trying to do is make the explosion of particles occur ever few seconds, but more then 2. It works great at 2 but is to short… Anyone know why its destroying it if x is changed???

error:
MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.

var explosion : GameObject;
var x = 2.0;// amount of seconds between iterations 

function Start (){
	emitParticles ();
}

function emitParticles () 
{ 
   while(true){ 
		explosion.particleEmitter.Emit(200);
		Debug.Log("Particle Emit Wait = "+ Time.time); 
        yield WaitForSeconds (x); 
    } 
}

EDIT:
Nevermind, damn autoDestruct was on in the particle Renderer!!! :lol: