Wednesday, October 23, 2019

architecture - How do I ensure a piece of code runs only once?


I have some code that I only want to run once, even though the circumstances that trigger that code could happen multiple times.


For example, when the user clicks the mouse, I want to click the thing:


void Update() {
if(mousebuttonpressed) {
ClickTheThing(); // I only want this to happen on the first click,
// then never again.
}

}

However, with this code, every time I click the mouse, the thing gets clicked. How can I make it happen only once?



Answer



Use a boolean flag.


In the example shown, you'd modify the code to be something like the following:


//a boolean flag that lets us "remember" if this thing has happened already
bool thatThingHappened = false;

void Update() {

if(!thatThingHappened && mousebuttonpressed) {
//if that thing hasn't happened yet and the mouse is pressed
thatThingHappened = true;
ClickTheThing();
}
}

Further, if you wanted to be able to repeat the action, but limit frequency of the action (i.e. the minimum time between each action). You'd use a similar approach, but reset the flag after a certain amount of time. See my answer here for more ideas on that.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...