In Unity, it is quite often to get a GameObject's component, such RigidBody or collision2D. There are a couple of ways of doing so, and GameObject.FindObjectOfType<>() ,GetComponent<>() are both frequently used.
GameObject.FindObjectOfType<>()
GameObject.FindObjectOfType<>() will search the entire scene for a component of the specified type. Therefore, which is way slower if we have a large amount of game objects in current scene, but it can be useful in some occasions, such as if you need to access a component that is not attached to the same GameObject as the script. For example:
GameManager gm = GameObject.FindObjectOfType<GameManager>();
Get the current GameManager in current scene.
GetComponent<>()
On the other hand, GetComponent<>() is used to obtain component(s) which attached to the same GameObject that the script is attached to. Therefore it is a much faster method to access a component as it only searches the current GameObject and its children. For example:
Rigidbody2D rb = GetComponent<Rigidbody2D>();
Get the Rigidbody2D of current game object.
**👉 If you want received more stories like this, please subscribe my channel to get the latest update in time.
Top comments (0)