- Home /
Alternative methods of running things only once in Update() besides bool check?
Hey everyone,
so I know that if you want to only run something once in Update() you would normally use a boolean within an if statement like so:
bool isDone = false;
void Update() {
if (!isDone) {
// code that runs once here
isDone = true;
}
}
If you have big scripts like me, it however becomes really messy at some point having plenty of different booleans that just serve as "checks" if or if not something has already been executed. I just thought to ask if there is any other way of doing this - although I guess there is not.
Thanks in advance!
Answer by Llama_w_2Ls · Oct 20, 2021 at 08:14 AM
Then just don't use update. Have a coroutine that waits a frame and calls all the code you need to run once. Call that coroutine from Start(), and it will run the same time as Update().
void Start()
{
StartCoroutine(DoThingsOnce())
}
IEnumerator DoThingsOnce()
{
yield return new WaitForEndOfFrame();
// Put code here..
}
sadly that doesnt help, since i need to constantly check if certain conditions are true in update to know when to run the script that i only want to run once.
Answer by Captain_Pineapple · Oct 26, 2021 at 03:29 PM
Why use a boolean flag in the first place?
I'd suggest that you put your code that you'd run if that flag is true into its own function.
Assuming that at some point you'd call yourclassObject.isDone = true
at the moment you should then just call yourclassObject.DoStuffWhenIsDone()
instead. No need for a flag and unnecessary checks in Update()
If you have a specific reason that this code has to be run in Update please let us know why and we might find a better solution.
Your answer
![](https://koobas.hobune.stream/wayback/20220613044406im_/https://answers.unity.com/themes/thub/images/avi.jpg)