Repeat something at a random interval

I’m trying to spawn enemies at random interval within a range.

At the moment I’m using InvokeRepeating to call function to spawn the enemy, however the interval is fixed and cannot be changed.

What would be the best way to repeat a function in a random interval?

4 Answers

4

I figured out an alternate way of doing it without using InvokeRepeating:

while(true)
{
  randomNumber = Random.Range(x, y);
  yield StartCoroutine("Wait");

  ExecuteFunction();
}

function Wait()
{
  yield WaitForSeconds(randomNumber);
}

That's along the right lines, but can be simplified a lot: while (true) { yield WaitForSeconds(Random.Range(x, y)); ExecuteFunction(); }

–

Ah, thanks Eric, I wasn't sure if we needed to use StartCoroutine as sometimes I find just using WaitForSeconds only work the first time, and the next time it just skips the waiting period. I guess it doesn't do that in this case

–

Actually it never does that; I would guess some kind of logic error.

–

While not knowing your current setup. I would use Random.Range.

var randomNumber : int;

function Update (){
randomNumber = Random.Range(0.5, 5);
    InvokeRepeating("Your function", 0, randomNumber);
}

It should be something along those lines.

I hope this clears it up a bit.

Yeah I was thinking about doing it like that but if you did it that way then InvokeRepeating will keep invoking the function at randomNumber intervals, where randomNumber is only randomised once at the very start. What I wanted was for randomNumber to be randomised at every interval. I actually figured out another way to do it using WaitForSeconds: I'll post it as an answer

–

That would start a new instance of the function every frame.

–

I’m not saying it’s the best way, but one way is to use a shorter interval, and randomly spawn during only some of those intervals.

Another thing you could try is to randomize an int inside the invoked method then check the value of the int for ‘x’ value to determine whether or not to run. For example:

public class whatever : MonoBehaviour 
{
    void Awake() 
	{
        InvokeRepeating("RandomRun", 2f, 2F);
    }
	
	void RandomRun()
	{
		int x = Random.Range(0,3);
		
		if( x == 0)
			DoMyStuff;
	}
}

In this example your event would have one chance in 3 of running every 2 seconds. Obviously you could increase the appearance of randomness by tweaking the variables.

Just a thought.