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

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.

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.