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