Downsides to if statement in Update()?

So I was having issues getting the ScoreDisplay in Laser Defender to bind to GameSession specifically when beginning the game in either the Start Scene or the Game Scene. It would be bound while playing the game and then would unbind when it loaded the Game Over Scene.

However, when I would begin loading from the Game Over Scene, it would bind correctly every time. I checked my Singletons to make sure everything was there properly, but I couldn’t get it to work as I intended from the Start or Game Scene. If you guys had any ideas on how to fix it, I’d appreciate it, but I have this code below in my ScoreDisplay.cs as a bandaid solution until I figure out how to fix it.

Also, are there any performance downsides to calling an if like this every frame, or does it only call this statement when it needs to?

    void Update()
    {
        if (!gameSession)
        {
            gameSession = FindObjectOfType<GameSession>();
            UpdateScore();
        }

    }

Hi Brennan, welcome to the community. :slight_smile:

It would be bound while playing the game and then would unbind when it loaded the Game Over Scene.

Can you post the singleton code you are using for the GameSession GameObject please.

However, when I would begin loading from the Game Over Scene, it would bind correctly every time.

Possibly because you have a GameSession GameObject in that scene and you are not carrying one over from a previous scene, as such your singleton logic doesn’t try to destroy anything.

Also, are there any performance downsides to calling an if like this every frame, or does it only call this statement when it needs to?

If you were calling the FindObjectOfType continuously in the Update method that would be extremely bad from a performance perspective. This method, as mentioned within the Unity documentation is slow, the reason for this, and any of the Find methods is that they have to traverse the entire scene comparing every GameObject until they find one that matches the type that you have specified.

With your if statement wrapped around this you have mitigated the issue partially, as the Find method will only be called until one is found, if of course you didn’t have one in the scene then this would be really bad again as that code would execute every frame, but then you’d probably hit a NullReferenceException error at some point, depending what is in the UpdateScore method.

You are, of course, still evaluating the condition within that if statement every frame, and that is certainly an overheard you should be able to remove. You should be able to Find the GameObject once within the Awake/Start methods.

The best solution here is that you do not have that if statement in the Update method at all.


See also;

Privacy & Terms