FindObjectsOfType

Several times throughout this course I made the mistake of using FindObjectOfType by mistake. This sets the var to something other than [ ]. In this lecture it sets a class. Just a missing ‘s’ but a big difference. Maybe I am the only one making this error but thought I would raise it.

Also in the Unity docs it says:

Please note that this function is very slow. It is not recommended to use this function every frame. In most cases you can use the singleton pattern instead.

1 Like

Hi Stephen,

This does come up from time to time, as the two methods are very similarly named and it is an easy mistake to make.

In the singular version, you are returned an object, the first it finds of the corresponding type. In the plural, an array of objects. Both assume the object is found.

Find/Get operations are not performance friendly typically, so where ever possible you want to reduce the necessity to call them.

As a bit of a noddy example, if you were updating a UI Text GameObject for a player’s score every time they shot a space ship, performing a GameObject.FindObjectOfType<Score>() would be expensive and unnecessary, as we could just make one call to that method in the Start method for example and then cache its reference using a variable. After that, all updates to score can be pushed through the variable instead of having to perform the find again and again.


See also;

Thank you Rob. I will go back over the lesson from the start as it has become a bit of a head scratcher. I also think I will go back to where the enemy GameObject is instantiated and see if I can add that GameObject to a list or something and provide it to the towers.

Thank you again

1 Like

I was making this mistake. Thank you, Stephen!

Privacy & Terms