Search Unity

Transform class vs. transform property

Discussion in 'Getting Started' started by m_ango, Nov 24, 2019.

  1. m_ango

    m_ango

    Joined:
    Jul 18, 2018
    Posts:
    6
    I read in the documentation that the Transform class inherits the transform property from the Component class. (https://docs.unity3d.com/ScriptReference/Transform.html) 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
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,128
    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.

    Code (csharp):
    1. public class ClassA : MonoBehaviour
    2. {
    3.     public ClassB classB;
    4.  
    5.     public void Awake()
    6.     {
    7.         classB.HelloWorld();
    8.     }
    9. }
    10.  
    11. public class ClassB : ClassA
    12. {
    13.     public void HelloWorld()
    14.     {
    15.         Debug.Log("Hello World");
    16.     }
    17. }
     
    m_ango likes this.
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    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.)
     
    m_ango likes this.
  4. m_ango

    m_ango

    Joined:
    Jul 18, 2018
    Posts:
    6
    That helped clear things up in my mind; thank you both!
     
    JoeStrout likes this.