Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
7  
I actually find this kinda of funny as I don't think it falls within "game-specific programming issues". But I never really liked that rule. – ClassicThunder Mar 25 at 23:33
3  
@ClassicThunder Yep, it's certainly more on the general programming side of things. Vote to close if you like, I posted the question more so we'd have something to point people to when they ask similar questions to this. It can be open or closed for that purpose. – Byte56 Mar 26 at 0:35
3  
PPCG's got you covered. – SirPython Mar 26 at 21:14

11 Answers 11

up vote 41 down vote accepted

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(mousebuttonpressed && !thatThingHappened) {
        //if the mouse is pressed and that thing hasn't happened yet
        ClickTheThing();
        thatThingHappened = true;
    }
}

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.

share|improve this answer
1  
The obvious answer to your question :-) I'd be interested to see alternative approaches if you or anyone else know of any. This use of a global Boolean for this has always been smelly to me. – Evorlor Mar 25 at 17:29
1  
@Evorlor Not obvious to everyone :). I'm interested in alternative solutions as well, maybe we can learn something not so obvious! – Byte56 Mar 25 at 17:32
2  
@Evorlor as an alternative, you could use delegates (function pointers) and change what action is made. e.g. onStart() { delegate = doSomething; } ... if(mousebuttonpressed) { delegate.Execute(); } and void doSomething() { doStuff(); delegate = funcDoNothing; } but in the end all options end up having a flag of some sorts you set/unset... and delegate in this case is nothing else(except if you have more than two options what to do perhaps?). – wondra Mar 25 at 17:50
2  
@wondra Yeah, that's a way. Add it. We might as well make a list of possible solutions on this question. – Byte56 Mar 25 at 18:00
1  
@JamesSnell More likely if it was multi-threaded. But still a good practice. – Byte56 Mar 25 at 21:49

Should bool flag not suffice or you wanted to improve readability* of the code in void Update() method, you could consider using delegates (function pointers):

public class InputController 
{
  //declare delegate type:
  //<accessbility> delegate <return type> <name> ( <parameter1>, <paramteter2>, ...)
  public delegate void ClickAction();

  //declare a variable of that type
  public ClickAction ClickTheThing { get; set; }

  void onStart()
  {
    //assign it the method you wish to execute on first click
    ClickTheThing = doStuff;
  }

  void Update() {
    if(mousebuttonpressed) {
        //you simply call the delegate here, the currently assigned function will be executed
        ClickTheThing();
     }
  }

  private void doStuff()
  {
    //some logic here
    ClickTheThing = doNothing; //and set the delegate to other(empty) funtion
  }

  //or do something else
  private void doNothing(){}
}

For simple "execute once" delegates are overkill, so I would suggest using bool flag instead.
However, if you needed more complicated functionality, the delegates are probably better choice. For example, if you wanted to chain execute more different actions: one on first click, other one on second and one more on third you could just do:

func1() 
{
  //do logic 1 here
  someDelegate = func2;
}

func2() 
{
  //do logic 2 here
  someDelegate = func3;
}
//etc...

instead of plaguing your code with tens of different flags.
*at cost of lower maintainability of the rest of the code


I did some profiling with results pretty much as I expected:

----------------------------------------
|     Method     |  Unity   |    C++   |
| -------------------------------------|
| positive flag  |  21 ms   |   6 ms   |
| negative flag  |  5 ms    |   7 ms   |
| delegate       |  25 ms   |   14 ms  |
----------------------------------------

The first test was run on Unity 5.1.2, measured with System.Diagnostics.Stopwatch on 32-bit built project (not in designer!). The other one on Visual Studio 2015 (v140) compiled in 32-bit release mode with /Ox flag. Both tests were run on Intel i5-4670K CPU @ 3.4GHz, with 10,000,000 iterations for each implementation. code:

//positive flag
if(flag){
    doClick();
    flag = false;
}
//negative flag
if(!flag){ }
else {
    doClick();
    flag = false;
}
//delegate
action();

conclusion: While the Unity compiler does a good job when optimizing function calls, giving roughly same result for both positive flag and delegates (21 and 25 ms respectively) the branch misprediction or function call is still quite expensive (note: delegate should be assumed cache in this test).
Interestingly, Unity compiler is not smart enough optimize the branch when there are 99 millions of consecutive mispredictions, so manual negating of the test does yield some performance boost giving best result of 5 ms. The C++ version does not show any performance boost for negating condition, however the overall overhead of function call is significantly lower.
most importantly: the difference is pretty much irrelevat for any real-world scenario

share|improve this answer
4  
AFAIK this is better from a performance point of view, too. Calling a no-op function, assuming that function is already in the instruction cache, is a lot quicker than checking flags, especially where that checking is nested under other conditionals. – Arcane Engineer Mar 26 at 9:40
2  
I think Navin is right, I it likely to have worse performance than checking boolean flag - unless your JIT is really smart and replaces whole function with literally nothing. But unless we profile the results, we cannot know for sure. – wondra Mar 26 at 19:29
2  
Hmm, this answer reminds me of the evolution of a SW engineer. Joke aside, if you absolutely need (and are sure) of this performance boost, go for it. If not, I'd suggest to keep it KISS and use a boolean flag, like proposed in another answer. However, +1 for the alternative represented here! – mucaho Mar 26 at 21:26
1  
Avoid conditionals where possible. I'm talking about what happens at the machine level, whether that's your own native code, a JIT compiler, or an interpreter. L1 cache hit is about the same as a register hit, possibly slightly slower i.e. 1 or 2 cycles, whereas branch misprediction, which happens less often but still too much on average, costs on order of 10-20 cycles. See Jalf's answer: stackoverflow.com/questions/289405/… And this: stackoverflow.com/questions/11227809/… – Arcane Engineer Mar 27 at 5:36
1  
Remember furthermore that these conditionals in Byte56's answer have to be called every single update for the lifetime of your program, and may well be nested or have nested conditionals within them, making matters far worse. Function pointers / Delegates are the way to go. – Arcane Engineer Mar 27 at 5:41

Some suggestions will vary depending on architecture.

Create clickThisThing() as a function pointer / variant / DLL / so / etc... and ensure that it is initialized to your required function when the object / component / module / etc... is instantiated.

In the handler whenever mouse button is pressed then call the clickThisThing() function pointer and then immediately replace the pointer with another NOP (no operation) function pointer.

No need for flags and extra logic for someone to screw up later, just call it and replace it every time and since it's a NOP the NOP does nothing and gets replaced with a NOP.

Or you could use the flag and logic to skip the call.

Or you could disconnect the Update() function after the call so the outside world forgets about it and never calls it again.

Or you have the clickThisThing() itself use one of these concepts to only respond with useful work once. This way you can use a baseline clickThisThingOnce() object / component / module and instantiate it anywhere you needed this behavior and none of your updaters need special logic all over the place.

share|improve this answer

Use function pointers or delegates.

The variable holding the function pointer need not be explicitly examined until a change needs to be made. And when you no longer need said logic to run, replace with a ref to an empty / no-op function. Compare with doing conditionals checks every frame for the entire life of your program - even if that flag was only needed in the first few frames after startup! - Unclean and inefficient. (Boreal's point about prediction is however acknowledged in this regard.)

Nested conditionals, which these often constitute, are even more costly than having to check one single conditional every frame, since branch prediction can no longer do its magic in that case. That means regular delays on the order of 10s of cycles - pipeline stalls par excellence. The nesting can occur above or below this boolean flag. I hardly need remind readers of how complex game loops can quickly become.

Function pointers exist for this reason - use them!

share|improve this answer
1  
We're thinking along the same lines. The most efficient way would be to disconnect the Update() thing from whoever keeps calling it relentlessly once it's done the work, which is very common in Qt style signal+slot setups. The OP didn't specify the runtime environment so we're hamstrung when it comes to specific optimizations. – Patrick Hughes Mar 27 at 6:39

In some script languages like javascript or lua can be easly done testing the function reference. In Lua (love2d) :

function ClickTheThing()
      .......
end
....

local ctt = ClickTheThing  --I make a local reference to function

.....

function update(dt)
..
    if ctt then
      ctt()
      ctt=nil
    end
..
end
share|improve this answer

For completeness

(Not actually recommending that you do this as it's actually pretty straightforward to just write something like if(!already_called), but it would be "correct" to do it.)

Unsurprisingly, the C++11 standard has idiomized the rather trivial problem of calling a function once, and made it super explicit:

#include <mutex>

void Update() {
if(mousebuttonpressed) {
    static std::once_flag f;
    std::call_once(f, ClickTheThing);
}

}

Admittedly, the standard solution is somewhat superior to the trivial one in presence of threads since it still guarantees that always exactly one call happens, never something different.

However, you aren't normally running a multithreaded event loop and pressing the buttons of several mice at the same time, so that thread safety is a bit superfluous for your case.

In practical terms, it means that in addition to the thread-safe initialization of a local boolean (which C++11 guarantees to be thread-safe anyway), the standard version must also do an atomic test_set operation prior to calling or not calling the function.

Still, if you like being explicit, there's the solution.

EDIT:
Huh. Now that I've been sitting here, staring at that code for some minutes, I'm almost inclined to recommend it.
Actually it is not nearly as silly as it may seem at first, indeed it very clearly and unambiguously communicates your intent... arguably better structured and more readable than any other solution which involves an if or such.

share|improve this answer

In a Von Neumann Architecture computer, memory is where your program's instructions and data are stored. If you want to make code only run once, you could have code in the method overwrite the method with NOP's after the method is complete. This way if the method were to run again, nothing would happen.

share|improve this answer
5  
This will break a few architectures that write protect program memory or run from ROM. It will also possibly set off random antivirus warnings, depending on what is installed. – Patrick Hughes Mar 27 at 6:57

In python if your planning on being a jerk to other people on the project:

code = compile('main code'+'del code', '<string>', 'exec')
exec code

this script demonestrates the code:

from time import time as t

code = compile('del code', '<string>', 'exec')

print 'see code object:'
print code

while True:
    try:
        user = compile(raw_input('play with it (variable name is code) (type done to be done:\t'), '<user_input>', 'exec')
        exec user
    except BaseException as e:
        print e
        break

exec code

print 'no more code object:'
try:
    print code
except BaseException as e:
    print e

while True:
    try:
        user = compile(raw_input('try to play with it again (type done to be done:\t'), '<user_input>', 'exec')
        exec user
    except BaseException as e:
        print e
        break
share|improve this answer

Here's another contribution, it's a little more general/reusable, slightly more readable and maintainable, but likely less efficient than other solutions.

Let's encapsulate our once-executing logic in a class, Once:

class Once
{
    private Action body;
    public bool HasBeenCalled { get; private set; }
    public Once(Action body)
    {
        this.body = body;
    }
    public void Call()
    {
        if (!HasBeenCalled)
        {
            body();
        }
        HasBeenCalled = true;
    }
    public void Reset() { HasBeenCalled = false; }
}

Using it like the example provided looks as follows:

Once clickTheThingOnce = new Once(ClickTheThing);

void Update() {
    if(mousebuttonpressed) {
        clickTheThingOnce.Call(); // ClickTheThing is only called once
                                  // or until .Reset() is called
    }
}
share|improve this answer

You can consider using static a variable.

void doOnce()
{
   static bool executed = false;

   if(executed == false)
   {
      ...Your code here
      executed = true;
   }
}

You can do this in ClickTheThing() function itself, or create another function and call ClickTheThing() in the if body.

It is similar to the idea of using a flag as suggested in other solutions, but the flag is protected from other code and cannot be altered elsewhere due to being local to the function.

share|improve this answer
1  
...but this prevents you from having the code run once 'per object instance'. (If that's what the user needs.. ;)) – Alexandre Vaillancourt Mar 30 at 13:01
    
@Evorlor I'm pretty sure it compiles, at least in c++. I don't like static variables, but when it's what you need, the option is there. Not sure why there is a downvote. – Alexandre Vaillancourt Apr 1 at 15:37

Stupid cheap way out but you could use a for loop

for (int i = 0; i < 1; i++)
{
    //code here
}
share|improve this answer
    
The code in the loop will always be executed when the loop is run. Nothing in there is preventing the code from being executed once. The loop or no loop gives exactly the same result. – Alexandre Vaillancourt Apr 1 at 16:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.