What is the best practice for cached references?

In a previous lecture, we cached the level variable as type Level and then assigned it later as level = FindObjectOfType<Level>();.

When creating the player score, we simply called AddToScore() by FindObjectOfType<GameStatus>().AddToScore();.

I understand that in the case of level, we were using it repeatedly throughout the script, but is it “wrong” or best practice not to create a cached reference for GameStatus, as well, and assign the FindObjectOfType to a variable? That’s what I did, because I didn’t know if it might be used again later, and I wanted to keep my code consistent.

That being said, the one line is definitely more concise and easy to see what’s happening immediately.

Is there a best practice in this case?

Hi Nathan,

I would consider the number of times that the referenced object is going to be used within your class. If you are only accessing something the once in a method then there isn’t really any use in making it a member variable, where every method in that class has access to it.

If you find yourself needing to access the referenced object more than once that’s the time to consider creating a member variable in the class to hold it’s reference, and just get it once.

This should be especially true of anything that you are using Unity’s Find methods for, this has to traverse the entire scene to find the GameObject(s) in question every time they are used, they are slow, and there is definitely a more performant approach to using this GameStatus object, e.g. create it once early on, only have one of them, don’t destroy it when another scene loads - removing the necessity to keep Finding it.

Also, using a statement like this;

FindObjectOfType<GameStatus>().AddToScore()

…is just a problem waiting to happen, it’s making too many assumptions - if that method doesn’t find a GameObject of type GameStatus it will return null, you will then be trying to access the AddToScore method on a null reference and receive a NullReferenceException error.

You could think of it this way, if you know there is a GameStatus object, because you are going to call AddToScore, then why are we finding it, we should already know about it, e.g. have a reference to it we can use.

Hope this helps :slight_smile:

2 Likes

Thank you for the explanation! That makes sense. As I was reading more about the different Find methods, I ran into a few conversations suggesting that they’re overused by programmers and there are usually better ways. That definitely explains more fully why we’d want to be more hesitant using Find. Looking forward to the rest of the course and learning how to optimize our code more. Very helpful!

1 Like

You’re very welcome Nathan, happy to help :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms