- Home /
How are you able to use a Transform argument for Instantiate?
I have been learning how to use Instantiate, but I have something that I am confused about. All of the examples I have found have used a Transform for the object argument. However, the documentation says that the argument takes an Object.
From what I understand, Transform is a part of an Object. If that is true, why am I able to create an entire Object from just its Transform?
Answer by Doireth · Jul 21, 2012 at 07:30 PM
In C# you can use:
Transform t = (Transform)Instantitate(something, somewhere, some rotation);
or
Transform t = Instantiate(something, somewhere, some rotation) as Transform;
The second technique is the more documented way to cast (convert) the returned GameObject object to a Transform.
In order to pass a transform as an argument to Instantiate
Instantiate(*transform*.gameObject, *location*, *rotation*);
EDIT: As Dave said, there may simply be an overloaded version of the function. I completely misunderstood what you were asking. Figured I would leave my code here just in case anyone wants to take the long way to do it.
Answer by whydoidoit · Jul 21, 2012 at 08:34 PM
Instantiate returns whatever you pass to it - but it's contained in an object variable. If you pass it a Transform you get back a Transform in an object variable and you can cast it using Instantiate(something, somewhere, someRotation) as Transform. But if you pass in a GameObject then you get back a GameObject stored in an Object and you must cast that to GameObject. Likewise any other type.
They aren't overloaded functions - it takes the type of the variable the prefab is and returns that that type - Object is just the ultimate base class of everything that Instantiate can create.
Your answer
Follow this Question
Related Questions
Trying to get a shoot function working in unity using instantiate and it isn't working. 1 Answer
Instantiate Object at the extreme end of the object 0 Answers
'transform' is not a member of 'Object' code problem 1 Answer
Putting prefab into scene messes with the transform origin? 1 Answer
The variable othertransform of Prefab has not been assigned 2 Answers