Best way to start a timer in a For Each loop?

I was wondering what the best way to start a timer once for each instance of an object within a For Each loop? Since you can’t use a Trigger Once in a For Each, the timer will reset on every frame without a further, more specific condition in the For Each. Right now, I’m using a timer and adding the action to start an object timer when the timer is within a VERY brief window of time, so that it’s kind of acting like a Trigger Once since the amount of time is so short. I tried using a boolean to do this, setting it to true, then starting the timer and setting it to false immediately after. However, I was still getting the effect of the timer resetting on every frame it seemed. So, what are some preferred ways to start a timer inside a For Each? Here is the code I have working right now, but I figure there has to be a better way:

There is a couple of ways you can achieve this. The first way is as you have already suggested, using your own “trigger once” system with a boolean object variable.


The second way is creating a custom behavior for the car that on creation sets up the timer.

Online Project: (6 months expiry)

1 Like

Thank you for the info and screenshots. I had a question about the code in the first screenshot that you posted.

When you initialize the timer of red_car_1, you check the value of its boolean _has_timer and set it to true. Then, in the subevent, you have it so that the timer “car_timer” will be starting/resetting on every frame. I was just wondering how this works if you’re resetting the timer on every frame in the subevent? Could you please explain how having the subevent in which you’re resetting the timer on every frame is working? I’m not doubting you, I’m just a bit confused by it. :slight_smile:

Hey @tjv189,

Sorry for the delay in getting back to you. In regards the INITIALIZE TIMER section we’re checking if the car has the _has_timer variable true, if not we set it to true and reset the timer.
You could move the action to the next sub event with the reset timer, but I tend to have my “trigger once” checks on the same event box.

See below (bit crude lol)

1 Like

Sorry for the delay in replying. Thank you so much for taking the time to spell out how GDevelop handles this sequence of actions. I never thought of doing it this way! It is working well so far.

1 Like

No problem.:smiley:
One thing to note is for the most part GDev reads top to bottom so the #5 (Check = True = Skip) would not be checked again for that frame.
Once the next frame is running and it gets to INITIALIZE TIMER that’s were it would skip that entire event block as it was set to true in the last frame.

1 Like