How would I always pick a new time for my timer?

Hey! So for my game i need an object to spawn between 1 second and 2 seconds. So i tried this and doesn’t seem to work.

local spawnRate = 1000 local function spawnObject() --Does different things here. Removed for better understanding. spawnRate = math.random( 1000, 2000 ) end timer.performWithDelay( spawnRate, spawnObject, -1 )

So the first time it spawns after 1 second but then it keeps spawning at 1 second. The math.random picks a new number but it doesn’t apply it to the timer.

–SonicX278 

It’s because the spawnRate is only applied when the timer function is first called. Try calling it recursively instead:

local spawnRate = 1000 local canSpawn = true local function spawnObject() --Does different things here. Removed for better understanding. spawnRate = math.random( 1000, 2000 ) if canSpawn then timer.performWithDelay( spawnRate, spawnObject, 1 ) else --do something else end end timer.performWithDelay( spawnRate, spawnObject, 1 )

Notice that I am calling the timer function using “1” each time I call it, not infinitely using “-1”. So each timer call is a new instance, and uses the spawnRate to set the length of time.

I’ve also added a bool that you can use to stop the spawning, as currently it would call timers non-stop. Set canSpawn to false when your level ends or whatever, and the timer will stop being called.

It’s because the spawnRate is only applied when the timer function is first called. Try calling it recursively instead:

local spawnRate = 1000 local canSpawn = true local function spawnObject() --Does different things here. Removed for better understanding. spawnRate = math.random( 1000, 2000 ) if canSpawn then timer.performWithDelay( spawnRate, spawnObject, 1 ) else --do something else end end timer.performWithDelay( spawnRate, spawnObject, 1 )

Notice that I am calling the timer function using “1” each time I call it, not infinitely using “-1”. So each timer call is a new instance, and uses the spawnRate to set the length of time.

I’ve also added a bool that you can use to stop the spawning, as currently it would call timers non-stop. Set canSpawn to false when your level ends or whatever, and the timer will stop being called.