Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have been following several tutorial series and have seen these two used in very similar ways, and was hoping someone could explain how they differ and, if possible, examples of when you would use one instead of the other (presuming that they are actually similar!).

private LevelManager levelManager;

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

and

private LevelManager levelManager;

void Start () {
    levelManager = GetComponent<LevelManager>();
}
like image 849
JonHerbert Avatar asked May 18 '15 18:05

JonHerbert


People also ask

What does GetComponent mean?

GetComponent will return the first component that is found and the order is undefined. If you expect there to be more than one component of the same type, use gameObject. GetComponents instead, and cycle through the returned components testing for some unique property.

Is GetComponent a method?

GetComponent()Unity provides us with a method that returns the Component of a GameObject that we want to get in order to access its properties or behaviour.


1 Answers

You don't want to use

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

that often. Particularly on start

To answer your question though, these two functions are actually not very similar. One is a exterior call, the other an interior.
So what's the difference?

  1. The GameObject.FindObjectOfType is more of a scene wide search and isn't the optimal way of getting an answer. Actually, Unity publicly said its super slow Unity3D API Reference - FindObjectOfType

  2. The GetComponent<LevelManager>(); is a local call. Meaning whatever file is making this call will only search the GameObject that it is attached to. So in the inspector, the file will only search other things in the same inspector window. Such as Mesh Renderer, Mesh Filter, Etc. Or that objects children. I believe there is a separate call for this, though.
    Also, you can use this to access other GameObject's components if you reference them first (show below).

Resolution:

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

private LevelManager levelManager;

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

Don't forget to tag the GameObject with the script LevelManager on it by adding a tag. (Click the GameObject, look at the top of the inspector, and click Tag->Add Tag

You can do that, or do

public LevelManager levelManager;

And drag the GameObject into the box in the inspector.

Either option is significantly better than doing a GameObject.FindObjectOfType.

Hope this helps

like image 100
iSkore Avatar answered Oct 20 '22 01:10

iSkore