How to find gameobject at runtime in unity?

Share on social media

In this article, we will see, How to find gameobject at runtime in unity using C#. I will explain each and every ways of finding game objects at runtime. So if you are interested then let’s begin.

Introduction

There are different ways to find gameobject at runtime in unity, We are gonna cover all of those ways in this article, So let’s start.

So first we will look at what are the actual ways to find gameobject at runtime in unity. So There are several ways of finding gameobject at runtime

Ways to find gameobject at runtime in unity

  1. Gameobject.Find.
  2. Resources.FindObjectsOfTypeAll.
  3. Find gameobject with tag.
  4. Transform.Find.
  5. transform.GetChild.

For instance, We will find this gameobject (shown in the image below) In different ways.

Find Gameobjects At Runtime In Unity C#
Find Gameobjects At Runtime In Unity C#

As you can see in the above image I have highlighted the “Destroy Obj” Gameobject, And we will be finding this gameobject through this article in different-different ways. So let’s start with our first way of finding gameobject at runtime.

First, we will see how to find gameobject with Gameobject.Find(“”).

1. Find gameobject with Gameobject.Find

 The first way to find gameobject at runtime in unity is the Gameobject.Find. In order to find our gameobject called “Destroy Obj”, Here is a simple code:

private void Start()
{
     GameObject objectToDestroy = GameObject.Find("Destroy Obj");
}

Here I have used this code in the Start function but you can use it where ever you need it, But if possible always try to do it in Start, Awake and OnEnable Function and try to avoid it using in loops or Update Function.

Note :- It will only work if the object that we are finding is active in the hierarchy, If your gameobject is not active in the hierarchy and you want to find it at runtime then you can try the other methods shown below.

But this way to find gameobject at runtime in unity is heavy when you use it in Update method, So try to always use in Start method and take a reference of it in variable and use it wherever you want it.

2. Resources.FindObjectsOfTypeAll

This function can return any type of Unity object that is loaded, including game objects, prefabs, materials, meshes, textures, etc. It will also list internal objects, therefore be careful with the way you handle the returned objects.

So through Resources.FindObjectsOfTypeAll you can also find the list of disabled objects in the scene as well. So here is the simple code of it.

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class ExampleScript : MonoBehaviour
{
    List<GameObject> GetAllObjectsOnlyInScene()
    {
        List<GameObject> objectsInScene = new List<GameObject>();

        foreach (GameObject go in Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[])
        {
            if (!EditorUtility.IsPersistent(go.transform.root.gameObject) && !(go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave))
                objectsInScene.Add(go);
        }

        return objectsInScene;
    }
}

This will return all GameObjects in the scene, in List<GameObject> format even if gameobject is disabled.

So this is the another way to find gameobject at runtime in unity.

3. Find gameobject with tag

In this way, You can find the gameobject with tags like “Player” or “Enemy”. Returns one active GameObject tagged with the tag you are looking for. Returns null if no GameObject was found.

Tags must be declared in the tag manager before using them. A UnityException will be thrown if the tag does not exist or an empty string or null is passed as the tag.

 Here is the code for finding gameobject with tag.

private void Start()
{
      GameObject objectToDestroy = GameObject.FindWithTag("Bullet");
      Debug.Log(objectToDestroy.name, objectToDestroy);
}

In the place of “Bullet”, You must replace it with your tag. It won’t find if gameobject is disabled.

4. Transform.Find()

This API will return the transform of the child transform or null if no child will be found. In this way, you can also find disabled gameobject in unity.

GameObject gun = player.transform.Find("Gun").gameObject;

You can also find the child of the child, For instance:-

Find Gameobjects At Runtime Through Transform.Find()
Find Gameobjects At Runtime Through Transform.Find()

Let’s say you want to find the “Cube3” (Highlighted with Blue) and your transform is “Cube” (Highlighted with Red). So It is possible through the ‘/’ character, It will access the Transform in the hierarchy like a pathname. Here is the example code

GameObject cube3 = transform.Find("@Cube (single mesh)/Cube3").gameObject;

This example is according to the image attached above. This way you can find the disabled gameobjects in unity.

5. transform.GetChild(Index)

This is used when we want to get a child by index and it returns a transform of a child by index.

If the transform has no child, or the index argument has a value greater than the number of children then an error will be generated. In this case “Transform child out of bounds” error will be given. The number of children can be provided by childcount.

Let’s see an example of transform.GetChild(). Let’s take the above image example that we used in transform.Find(). So we want to find “Cube 3” again.

So here is the simple code of it.

GameObject cube3 = transform.GetChild(0).GetChild(2).gameObject;

So this is also the great way to find gameobject at runtime in unity.

You can check this in the above image and match the indexes.

So these are the Ways to find gameobject at runtime in unity. And if you know any other way to find gameobject at runtime in unity, So I will be glad if you share that in the comment section below.

Hope guys this was helpful and may have learned something new today, Stay tuned for new topics.

So what way you prefer to find gameobject at runtime? Comment down 

If you have an issue or query you can contact me. Thank You.

You can also read our other topics like – Coroutines, Camera Shake, Camera Follow, Camera Clamping, etc.

Aakash Solanki
Aakash Solanki

I am a professional unity game developer. I have a passion for creating immersive gaming experiences. For me writing articles feels like giving back to the community we have learned from. My hobbies involve playing games and writing articles and sometimes I also create youtube videos.


Share on social media

1 thought on “How to find gameobject at runtime in unity?”

  1. Pingback: Unity Gameobject Find | Unity C# Tutorial - Basics: Gameobject.Find() 10296 좋은 평가 이 답변

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top