Search code examples
c#unity-game-enginegenericsinstantiation

Why does instanciating a Transform class creates a new GameObject?


So I was following a tutorial and noticed that the person used Transform to instantiate a new gameObject from a prefab:

private List<Transform> segments = new List<Transform>();
//segment prefab is a prefab added from the unity editor
public Transform segmentPrefab;

public void Grow()
{
    Transform segment = Instantiate(segmentPrefab);
    segment.position = segments[segments.Count - 1].position;
    segments.Add(segment);
}

And after calling Grow from another function, a new GameObject that uses the segmentPrefab prefab is instantiated and appeared on the screen.

I am aware of the fact that this person used generic method of instantiate, but I am confused about why instantiating Transform creates a new GameObject. I thought Transform class only serves as a property of GameObject, not a complete object. Do I have some misunderstanding of GameObjects in unity?


Solution

  • From Object.Instantiate

    If you are cloning a Component the GameObject it is attached to is also cloned, again with an optional position and rotation.

    When you clone a GameObject or Component, all child objects and components are also cloned with their properties set like those of the original object.

    And Transform is a Component.

    In simple words:

    Because it wouldn't make any sense at all to create an instance of a Component without that Component being attached to any GameObject.

    -> What exactly would you do with only a Transform (or any other Component) that isn't attached to anything? ;)

    That's also the reason why new is forbidden on any class deriving from Component as they need to be created by the underlying c++ engine and be connected to a GameObject.

    Have in mind that the entire Unity engine is actually in c++. Whatever you do in c# is just an API layer on top of that c++ engine core to make it easier to use for us developers