GameObject.FindObjectOfType <> () vs GetComponent <> ()

I followed several training series and saw that the two are used in very similar ways, and hoped that someone could explain how they differ and, if possible, examples of when you will use one instead of the other (assuming that they really similar!).

 private LevelManager levelManager; void Start () { levelManager = GameObject.FindObjectOfType<LevelManager>(); } 

and

 private LevelManager levelManager; void Start () { levelManager = GetComponent<LevelManager>(); } 
+5
source share
2 answers

You do not want to use

 void Start () { levelManager = GameObject.FindObjectOfType<LevelManager>(); } 

that often. In particular, at start

To answer your question, these two functions are not really very similar. One is an external challenge, the other is an interior.
So what's the difference?

  • GameObject.FindObjectOfType is a broader scene search and is not the best way to get an answer. In fact, Unity has publicly stated that its super slow Unity3D API Reference is FindObjectOfType

  • GetComponent<LevelManager>(); is a local call. The value of any file that makes this call will be searched only by the GameObject to which it is bound. Therefore, in the inspector, the file will search only for other things in the same inspector window. Such as Mesh Renderer, Mesh Filter, etc. Or are these objects for children. I believe that there is a separate appeal for this. In addition, you can use this to access other GameObject components if you first access them (see below).

Resolution:

I would recommend doing a tag search in the awake function.

 private LevelManager levelManager; void Awake () { levelManager = GameObject.FindGameObjectWithTag ("manager").GetComponent<LevelManager>(); } 

Remember to tag the GameObject with the script LevelManager by adding a tag. (Click GameObject, look at the top of the inspector and click "Tag-> Add Tag"

You can do it or do it

 public LevelManager levelManager; 

And drag the GameObject into the inspector window.

Any option is significantly better than executing GameObject.FindObjectOfType .

Hope this helps

+10
source

There are two differences:

1.) GetComponent<T> finds a component only if it is bound to the same GameObject. GameObject.FindObjectOfType<T> , on the other hand, searches for an entire hierarchy and returns the first object that matches!

2.) GetComponent<T> only returns an object that inherits from Component , while GameObject.FindObjectOfType<T> all the same.

+5
source

All Articles