ruk·si

⬜️ Unity
Finding Game Objects

Updated at 2016-10-30 09:55
using UnityEngine;
using System.Collections;

public class FlowDriver : MonoBehaviour
{
    private void Start()
    {
        var go = gameObject;

        // These are all fast.
        //
        // get a component from this game object      (1 component or null)
        go.GetComponent<Texture>();
        // get a component from hierarhcical children (1 component or null)
        go.GetComponentInChildren<Texture>(true);
        // get a component from hierarchical parents  (1 component or null)
        go.GetComponentInParent<Texture>();

        // These are also fast.
        //
        // get components from this game object       (list of components)
        go.GetComponents<Texture>();
        // get components from hierarhcical children  (list of components)
        go.GetComponentsInChildren<Texture>(true);
        // get components from hierarchical parents   (list of components)
        go.GetComponentsInParent<Texture>(true);

        // OK performance
        //
        // global tag search  (1 object or null)
        // global tag search  (list of objects)
        GameObject.FindGameObjectWithTag("Player");
        GameObject.FindGameObjectsWithTag("Enemy");

        // Pretty slow, both of them.
        //
        // global name search (1 object or null)
        GameObject.Find("MainHeroCharacter");
        // child name search  (1 transform or null)
        transform.Find("Gun");

        // Slow, but sometimes necessary.
        //
        // global type search (1 object or null)
        GameObject.FindObjectOfType<Texture>();
        // global typ search  (list of objects)
        GameObject.FindObjectsOfType<Texture>();

        transform.SetAsFirstSibling();
        transform.SetAsLastSibling();
        transform.SetSiblingIndex(5);
    }
}

You can use casting + LINQ for more complex lookups:

using System.Linq;
using UnityEngine;

public class Looper : MonoBehaviour
{
    private void Start()
    {
        foreach (Transform t in transform) {
            Debug.Log(123);
        }

        var flowFragmentNode = gameObject
            .GetComponentsInChildren<FlowFragment>()
            .Select(e => e.GetComponent<Node>())
            .FirstOrDefault(n => n.Id == flowFragmentRef.IdRef);

        var folderNode = transform
            .Cast<Transform>()
            .Where(t => t.GetComponent<Node>() != null)
            .Select(t => t.GetComponent<Node>())
            .FirstOrDefault(n => n.Id == folderRef.IdRef);
    }
}

Sources