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

前端 未结 2 952
孤独总比滥情好
孤独总比滥情好 2020-12-24 15:10

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, examp

2条回答
  •  隐瞒了意图╮
    2020-12-24 15:56

    There are two differences:

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

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

提交回复
热议问题