- Home /
Get Component that a GameObject is Attached To
I have GameObject A.
GameObject A has Component B attached to it. Component B is just a Script. Component B has GameObject C as a public variable.
GameObject C is just an empty GameObject with a Script attached to it.
How do I reference Component B from GameObject C? How do I reference GameObject A from GameObject C?
(I know this is a little confusing, and I apologize. I tried to simplify it as much as possible.)
If I get this right you are asking to climb backwards up the references? This can't be done through normal program$$anonymous$$g methods. There may be some bizarre reflection techniques that allow this.
Answer by rutter · Sep 16, 2014 at 11:48 PM
The structure you've described has available references like so:
GameObject A
^
|
v
Script B -------> GameObject C
^
|
v
Script D
From A, you can find B.
From B, you can find A or C.
From C, you can find D.
Unfortunately, there is no reference from C back to B, which makes the question as stated difficult or impossible.
You may be able to find another solution:
Are A or B unique within your scene? If so, you may be able to look them up by tag, name, or singleton instance.
Can you add a reference from D back to B? You could set this reference in the inspector, or from a script.
Can B notify D that it exists? This would allow you to cache a reference.
Since you haven't described the scenario in much detail, beyond the available references, vague suggestions are about the best I can give.
That general answer is exactly what I needed to learn. Thank you very much! Very informative and helpful!!
Answer by orb · Sep 16, 2014 at 11:49 PM
If A has a unique name (if it doesn't, how would it even be possible to get it?), get it like this in object C's script:
GameObject aye = GameObject.Find("Object A"); // Replace with the name of your object, of course :)
Then get the component:
ComponentB bee = aye.GetComponent<ComponentB>();
You should check that aye is actually not null before getting the component.
Your answer
Follow this Question
Related Questions
Can I move a component from one GameObject to another in script? 1 Answer
How to mimic Unity's Components based System 1 Answer
How to Check if a component Exists on a Gameobject. 3 Answers
Storing component of instance in an array 2 Answers
How to get a List of references of instances in a static variable 1 Answer