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

戏子无情 提交于 2019-11-27 01:25:11

问题


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>();
}

回答1:


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




回答2:


There are two differences:

1.) GetComponent<T> finds a component only if it's attached to the same GameObject. GameObject.FindObjectOfType<T> on the other hand searches whole hierarchy and returns the first object that matches!

2.) GetComponent<T> returns only an object that inherits from Component, while GameObject.FindObjectOfType<T> doesn't really care.



来源:https://stackoverflow.com/questions/30310847/gameobject-findobjectoftype-vs-getcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!