How to find a GameObject in Unity

There are three simple methods that you can use to find the gameobject in Unity.

  1. GameObject.Find
  2. GameObject.FindWithTag
  3. GameObject.FindGameObjectsWithTag

GameObject.Find finds the gameobject with its name. You just need to specify the name of the gameobject as a string.

This method searches all active scenes and returns only active gameobjects. It should not be used in an Update function as its effects performance. It’s recommended to use it in Awake or Start. If you need to find an object that’s instantiated in between you can use it in Update with a condition.

GameObject my_object=GameObject.Find("My_object");

GameObject.FindWithTag finds the first active gameobject with the tag specified. This function is good to use if you have a single gameobject tagged.

GameObject my_object=GameObject.FindWithTag("Object_tag");

GameObject.FindGameObjectsWithTag returns an array of objects with the specific tags. This is very useful when you need to perform a single action on similar objects. Like increasing the health of all enemies when a milestone is achived.

GameObject[] my_object=GameObject.FindGameObjectsWithTag("object_tag");

There is no way to find an inactive game object in Unity. If you think you need to access the inactive gameobjects then it’s better to reference them using a public gameobject.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.