Repeat method once in a time

I’ve tried to use InvokeRepeating to execute a method each time, but I wanted this time to change and, since it wouldn’t change in the Start() method, I tried the InvokeRepeating at Update(). Since Update() is continuously repeated , I also didn’t get what I wanted. Then I tried to create this timer:

public float timer;
public float currentTime;

void Start()
{
currentTime = 0;
timer = 0;

}

void Update () {
currentTime += Time.deltaTime;

if (currentTime == timer) {
spawn();
timer += spawnTime;
}

}

*The spawnTime changes.
It hasn’t worked (It was ony executed when currentTime = 0). What can I do to fix It?

Just some code off my mind, you’ll have to check for errors in syntax, but the idea is simple.

static float next_invoke_time=1;
void Awake(){
  StartCoroutine("InvokeAfterTime");
}

IEnumerator InvokeAfterTime(){
  yield return new WaitFor(next_invoke_time);
  //now your method is being exectued after time.
  //you can change the next_invoke_time here too.
}
1 Like

@Danilo-45 , please use code tags. Otherwise your code is really hard to read!

Your code doesn’t work because curretnTime overshoots timer. If you set timer to eg. 2, currentTime will never be exactly 2, it’ll be something like 1.99435 and then 2.053411.

The easiest fix is just to replace == with >=. You want to have the spawn happen on the first frame after the timer is up.

You also don’t really need the currentTime variable. There’s a build-in value, Time.time, which is exactly the same thing.

1 Like

@Baste

It has worked perfectly! Thank you!