Transform class vs. transform property

I read in the documentation that the Transform class inherits the transform property from the Component class. (Unity - Scripting API: Transform) And the transform property is of type/class Transform.

I thought I understood the concept of inheritance, but this circular dependency confuses me.

Can a base class contain an instance of a derived class?

If I do:
Transform a
What’s the difference between these two:
a
a.transform

Yes, but I have to admit before reading this thread it never stood out as odd to me even though it is. Below is the code that I used to verify it on my end but it was very clear before I tested it that it would work simply because it’s being done by Unity.

public class ClassA : MonoBehaviour
{
    public ClassB classB;

    public void Awake()
    {
        classB.HelloWorld();
    }
}

public class ClassB : ClassA
{
    public void HelloWorld()
    {
        Debug.Log("Hello World");
    }
}
1 Like

Sure, why not?

There is no difference, except that the second one is slightly wasteful. The transform method on any component simply goes to the GameObject the component is on, and finds the Transform component of that GameObject, and returns it. In the case above, that’s a walk from a to its GameObject and back to a.

Note that Transform is a bit special, as every GameObject is required to have exactly one of these. So when I say “finds the Transform,” that doesn’t imply a search — I would imagine, under the hood, a GameObject always knows where its Transform is. (Insert obscure Hitchhiker’s Guide to the Galaxy reference here.)

1 Like

That helped clear things up in my mind; thank you both!

1 Like