Download

Beginner programming question. Best approach for continously checking but only executing once?

Hello! So I am starting to feel like I have a decent grasp on C++ basics, but I’ve noticed that I’m starting to accumulate a ridiculous amount of bools and I think there’s probably a better way to approach this.

Basically, I have a lot of bool checks in my tick to see if a piece of code should be executed or not. Most of these blocks of code/functions can be run repeatedly each tick, but only really need to be done once, until something has changed and it needs to be run again.

The way I currently do this is basically to make a bool for each block of code I wish to execute, and change it each time I want it to run. But I feel like this is a messy and inefficient approach.

E.G:


bool ATribesmenCharacter::bIsAFK()
{
if (float TimeSinceInput = GetWorld()->GetRealTimeSeconds() - LastInputTime >= ToggleAFKTime)
{
ActivateOrbitCam(true);
return true;
}
else
return false;
}



This is checked each tick. But I only want ActivateOrbitCam to run once while true.
To do this, I would add a bool to my ActivateOrbitCam function to check if it is already active, if not, it’s skipped.

Is there a better way to do this?

Try use GetWorld()->GetTimerManager().SetTimer, set looping to true

Yes a timer would be a lot better in your case, you don’t need this to tick. Something like 5 seconds or even 10 seconds is enough. As for your “DoOnce” you could just GetWorldTimerManager.ClearTimer();

To get back from AFK state, try setting a delegate on any input? and then run the timer again.

Thanks for the tip about the timers! I wasn’t aware of those functions.

But I’m afraid a timed event is only one example, I’m more refering to how to only run a piece of code once that’s being checked for to trigger continously in tick, other than adding more and more booleans.

Whatever your trigger is, turn that into a delegate. The delegate system is good for the situation you are describing, but it works in the opposite direction – rather than constantly checking for a change in some condition, the condition shouts out to the world that it has changed, and anything that has been assigned to care about that change then initiates whatever behavior is supposed to begin based on that change.

Thanks, I’ll look into delegates!