Calling a function every 2 seconds

Does anyone know a good way I can call a function every two seconds so I can control the speed at which I my Ball objects across the screen.

I already have a function to instantiate the objects I just need a way to call it at specified time intervals , is it possible to make these values a little varied using something like Random.Range?

what is it exactly that your ball is doing? Is it something bouncing around the screen?

You could do something like this:

private var gapTest = true;

function Update () {
    if (gapTest) {
        // do your stuff here option 1
        GapSet ();
    }
}

function GapSet () {
    gapTest = false;
    // do your stuff here option 2
    yield WaitForSeconds (2);
    gapTest = true;
}

InvokeRepeating(“MyFunction”, .01, 2.0);

function Start () {
    while (true) {
        yield WaitForSeconds(Random.Range(1.0, 2.0));
        // do something
    }
}

–Eric

Thanks very much for the advice guys, I took it all on board and it seems to be working nicely :smile:

Eric, is there any reason you wouldn’t simply do it like this…

function Start()
{
 gapSet();
}

function gapSet()
{
 while(true)
 {
 yield WaitForSeconds(Random.Range(1.0,2.0);
  // Do stuff
 }
}

While i’m sure the performance difference between the two isn’t even measurable, I’m just curious as to why you’ve done it that way :slight_smile:

Considering they are exactly the same, I’m sure too. :wink:

Takes less time to type, uses a few bytes less memory…

–Eric

Just in case somebody comes to here since we have a beautiful function now in 2016:

That looks very similar to @Eric5h5 's answer in this thread (made in 2010) :wink:

Holy Molly sorry yea it did exist since 2010… (i’ve been an dumbass for nearly 6 years…)

Well You can just invoke the function in Update method:

void Update ()
{
Invoke(“Ball”, 2f);
}

I didn’t know what you function was called, so replace “Ball” with your function name.