#What's the difference between GetComponent and FindObjectsOfType?

1 messages · Page 1 of 1 (latest)

gloomy sedge
#

I can use both without any errors. What's the difference? Can you give an example?

abstract lily
#

GetComponent returns a component of the specified type that lives on the object executing the code

FindObjectOfType returns a component that lives on any object in the scene, it returns the first match it finds. For this reason we heavily discourage you from using it because it can be extremely unperformant

#

As the more objects you add to your scene, the more objects it has to search - and therefore the slower it becomes

cosmic narwhalBOT
#

Don't use Find methods!

Find methods in Unity are an often-tempting solution to referencing a scene object. However, there is always a better solution.
Whenever you call a Find method, Unity must traverse your entire scene hierarchy and check every single object until it finds a match; and the methods which return arrays will always traverse the entire hierarchy regardless.
This is inefficient! It means that the more objects you add to your scene, the slower these methods become; and it gets even worse if you are calling them multiple times.

A non-exhaustive list of Find methods to avoid:
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html

To read about a better solution, type []getareference or []getref

abstract lily
#

GetComponent also has its issues, you should assign a reference in the inspector if you can. But it's not nearly a big of an issue as Find... methods