Calling a function in Update once every time when the condition is met?

I have a game in which one random item is spawned when a timer reaches zero. This is currently in the Update function as it needs to check the timer every frame. But when timer reaches zero, it spawns multiple items because it is in the Update function. I have tried:

if(!singleExecution)
{
        
           if(this condition is met)
           {
                     execute this action;
           }

           singleExecution = true;

}

this allow the function to be executed once in the Update function when the condition is met the first time. However it does not get executed once every time the condition is met, which exactly is what I need. So Update function doesn’t work, what does?

You have an error there. What if the condition isn’t met but the timer still reached zero? Then the inner if statement will be discarded BUT the boolean singleExecution will still set to be true.

This is how it should be:

if (!singleExecution)
 {
     if(this condition is met)
     {
        singleExecution = true;   // This boolean should be inside the if statement
        execute this action;
     }
 }

@allenallenallen pointed out the first issue with your logic, however I think you are also saying that you want your code to:

  1. ‘execute this action’ once when the condition is first met
  2. wait until it is no longer met
  3. ‘execute this action’ when it is met again
  4. goto 2

To do this, you would take a similar fix to the one proposed by @allenallenallen :

//check if the condition is currently met
if(this condition is met)
{
    //it is met, so check if we have executed yet
    if(!singleExecution)
    {
        //we hadn't executed yet, so set the single execution bool and execute
        singleExecution = true;
        execute this action;
    }
}
else
{
    //it isn't met, so clear out 'singleExecution' bool
    singleExecution = false;
}

-Chris