Find a GameObject by its name in Unity C#

To find a GameObject in Unity with the help of C# programming, we can use the GameObject.Find() method. We have to pass the object name as a parameter to this method just as you can see in the syntax below:

GameObject.Find("OBJECT_NAME");

In the above syntax, OBJECT_NAME is the name of your GameObject you want to find in runtime. We have to check if the value is null or not.

Before going further, let’s see an example:

using UnityEngine;

public class FindGameObject : MonoBehaviour
{
    void Start()
    {
// Get the GameObject by object name GameObject myGameObject = GameObject.Find("OBJECT_NAME"); if (myGameObject != null) { Debug.Log("Object " + myGameObject.name + " Found"); } else { Debug.LogWarning("Sorry, Object " + myGameObject.name + " Was Not Found"); } } }

In the above C# program, I first created a reference of the object with the object name and stored it in myGameObject  variable. When the GameObject with the provided object name exists in the scene, it returns the object reference, otherwise, it returns null value.

In our code, I am using the if…else statement to determine if the value  myGameObject is not null, which returns a message in the console, otherwise returns another message in the console to show a warning message. Look at the code above for a better understanding.

Leave a Reply

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