Script Object Heirarchy

Just getting started with Unity (so far so good), and I have a quick question regarding the object heirarchy. When I drag a C# script to an object in my scene (a cube for example), what’s the top-level container object that the script is then associated with? It certainly feels like the cube is a GameObject because you can do things like the following:

this.transform.blah(…);

or even

transform.blah(…);

But there’s also a property called gameObject as well.

gameObject.transform.blah(…);

Is there some outer countainer encapsulating gameObject and other members as well, and where can I find the docs on this? As a quick aside, I’m really impressed with Unity overall. Great product!

“gameObject” is equivalent to “this” for any class that inherits from MonoBehaviour. It represents the GameObject that script is attached to. It can also be omitted, as you’ve seen.

Where it comes in handy is if you need to traverse up from a lower-level component in another script.

For example:

public Transform OtherTransform; // assign via Inspector

void DoSomething()
{
    // disable the GameObject 'OtherTransform' is attached to
    OtherTransform.gameObject.SetActive(false);
}

Perfect explanation. Thanks for the help!