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!

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().

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.