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 Find
ing 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