10 Ways to find a GameObject using Script in Unity

Here are 10 unique ways to find a single Game Object in unity

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

public class PlayerController : MonoBehaviour
{

    public GameObject findIt;
    void Start()
    {
        // Find GameObject by Name
        // This searches for a GameObject with the name "ByName".
        findIt = GameObject.Find("ByName");

        // Find GameObject by Tag
        // This searches for the first GameObject with the tag "Player".
        findIt = GameObject.FindWithTag("Player");

        // Find GameObject by a Component attached to it
        // This finds the first GameObject with a BoxCollider2D component attached to it.
        findIt = FindObjectOfType<BoxCollider2D>()?.gameObject;

        // Find GameObject by a Script attached to it
        // This finds the first GameObject with a CustomScript component attached to it.
        findIt = FindObjectOfType<CustomScript>()?.gameObject;

        // Find GameObject by Layer
        // This finds the first GameObject in the specified layer "customlayer".
        findIt = FindObjectsOfType<GameObject>().FirstOrDefault(g => g.layer == LayerMask.NameToLayer("customlayer"));

        // Find GameObject by an order in the scene
        // This finds the first root GameObject in the active scene.
        findIt = SceneManager.GetActiveScene().GetRootGameObjects().ElementAtOrDefault(0);

        // Find Child GameObject with a specific parent
        // This finds the child GameObject named "ByChild" under the parent named "Parent".
        findIt = GameObject.Find("Parent")?.transform.Find("ByChild")?.gameObject;

        // Find Parent GameObject with a specific child
        // This finds the parent GameObject that has a child with the name "SpecificChild".
        findIt = FindObjectsOfType<GameObject>().FirstOrDefault(go => go.transform.Cast<Transform>().Any(child => child.name == "SpecificChild"));

        // Find Child GameObject using index
        // This finds the third child (index 2) of the GameObject named "ByChildIndex".
        findIt = GameObject.Find("ByChildIndex").transform.GetChild(2)?.gameObject;

        // Find GameObject by specific property of a component
        // This finds the first GameObject with a BoxCollider2D component where the isTrigger property is true.
        findIt = GameObject.FindObjectsOfType<CircleCollider2D>().FirstOrDefault(s => s.isTrigger == true)?.gameObject;


    }


}
Share your love