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

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:

GameController <--- i want the component on this GameObject
GrandParent¬
    Parent¬
        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 ?

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>()

1 Like

You could also try

MyComponent comp = transform.parent.parent.GetComponent<MyComponent>()

comp.SomeMethod()

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):

Unity3D Singleton with Prefab used for predefined data:

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

2 Likes