- Home /
Efficient way for calling a function once
Hi, I know there are some ways for calling a function once. The most common one:
bool functionCalled = false;
void Update () {
if (!functionCalled && AfterSomeTime) {
doSomething ();
functionCalled = true;
}
}
However this is not efficient since the if statement checks during the whole game. After the function is called, you just waste processing power with the always-false if statement. It may seem insignificant but it may accumulate if you use that a lot. Is there an efficient way for calling a function once?
Based on how AtferSomeTime is set you can pass a delegate or simply call your method once it is done.
One slight improvement already would be to place the AfterSomeTime first since it is the one most likely to be false at first. But all that is micro optimization. A bool check will not change much of your app, even if you have hundreds of them.
But, for your question, you should let us know how AfterSomeTime is set and from there, it is easier to say.
Let's say
if (!functionCalled && Time.realtimeSinceStartup>10)
placing it first will be worse in this case since it will be true forever after function call.
Answer by fafase · Apr 11, 2015 at 04:13 PM
Use Invoke with a timer so that Unity takes care of the optimization:
void Start(){
Invoke("doSomething ", 10f);
}
This way not only you don't have to care about the check but you don't need the boolean anymore.
Answer by KalleH · Apr 11, 2015 at 03:55 PM
If statemenets don't really take any time at all so you shouldn't be worried of them even if you had plenty of them. The biggest problem is probably just that the code itself might look a bit messy but it shouldn't have any major impact on the performance. The way you used is probably the best one for this (please someone correct me if there is another way but I'm 99% sure that this is the way to go). Also you could use Start and Awake functions if the code has to be executed in the beginning of the game.
Answer by dynamoo21 · Feb 04, 2017 at 07:13 AM
It all depends on your requirement, Updates are best suited for taking constant input for constant output. Another alternative is to use coroutines for example.
bool isActionPerformed;
IEnumerator CoroutineName(){
while(!isActionPerformed){
yield return new WaitForEndOfFrame ();
//Logic here
//toggle the boolean whenever you acheive your objective
isActionPerformed = true;
}
}
Your answer
Follow this Question
Related Questions
Calling A Function Once 0 Answers
Calling a function only once in Update 3 Answers
Events called every Nth day 1 Answer
Call function after script compilation? 2 Answers
How to call a function from a script component on another object 1 Answer