Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

How do you get a component reference not part of its heirarchy?

Discussion in 'Scripting' started by TheCelt, Jan 21, 2021.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    723
    Hello

    I am aware of GetComponent, GetComponentInParent and GetComponentInChild

    But what if the component i need is outside of all of these options such as this kind of hierarchy:

    Code (CSharp):
    1. GameController <--- i want the component on this GameObject
    2. GrandParent¬
    3.     Parent¬
    4.         MyScript <--- this is the component seeking it
    I need to link them via code not the inspector approach but not sure how i would do it ?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,724
    GameController sounds like a prime candidate for the Singleton pattern, assuming you only have one of them.

    You could also use
    GameObject.FindGameObjectByTag("sometagthatyougiveyourgamecontrollerobject").GetComponent<GameController>()
     
    Joe-Censored likes this.
  3. juiced12

    juiced12

    Joined:
    Nov 8, 2018
    Posts:
    44
    You could also try

    Code (CSharp):
    1. MyComponent comp = transform.parent.parent.GetComponent<MyComponent>()
    2.  
    3. comp.SomeMethod()
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    Totally agree there... here's what I would use:

    Simple Singleton (UnitySingleton):

    Some super-simple Singleton examples to take and modify:

    Simple Unity3D Singleton (no predefined data):

    https://pastebin.com/SuvBWCpJ

    Unity3D Singleton with Prefab used for predefined data:

    https://pastebin.com/cv1vtS6G

    These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
     
    PraetorBlue and Joe-Censored like this.