- Home /
Instantiate Typecasting
I am using Javascript and Unity iPhone to Instantiate a game piece. It works fine in the desktop version, but on the iPhone it doesn't work because it isn't the same type.
I am trying to parent this spawned object to a board, but Instantiate returns an Object and not a GameObject/transform, so I can't access the parent property. I read that a Transform is actual returned by Instantiate, but I can't typecast like you can in C#:
C#
Transform piece = (Transform)Instantiate(..); // I usually use JS, this may not be 100% correct
But this does not work in Javascript, and in standard Javascript you usually do Number(...) or .toString, etc. How would I set the parent of this spawned object using Javascript, or how would I typecast it to a transform?
Answer by qJake · Jul 29, 2010 at 03:05 AM
var returnedObj : Transform;
returnedObj = Instantiate(...);
Is that what you want to do? Your question was sort of unclear.
This is what the question seems to be asking. The use case is very similar to the Projectile RigidBody instatiation example in the documentation. http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html
Answer by Patrick Lynch · Apr 24, 2011 at 04:57 AM
You've got to cast it to a transform, then you can get the gameObject or any other components.
Transform g = (Transform) Instantiate(indicatorPrefab, new Vector3(0,0,0), Quaternion.identity); GameObject obj = g.gameObject; GUITexture gui = g.gameObject.GetComponent();
Answer by JoeStrout · Feb 01, 2011 at 06:05 PM
But if you have #pragma strict on, then this doesn't work. Or at least, it doesn't for me. So I have the same question: how do you typecast from a more general type (Object) to a more specific type (e.g. GameObject), in order to satisfy the strict typechecking?
Answer by Techsuport · Aug 12, 2011 at 03:45 AM
var thing:GameObject=Instantiate(prefabThing,pos,rot) as GameObject;
this will not give errors with #pragma strict. another on to look out for is the for(thing in things) loop.
for(var thing:GameObject in things as Gameobject)
i think that'll work
Your answer
![](https://koobas.hobune.stream/wayback/20220613070005im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
TPS Camera with Joystick (Android) 0 Answers
Flipping textures 0 Answers
Multitouch iPhone error! Help 1 Answer
Unity iPhone and Unity Desktop Scripting Differences 2 Answers
iPhone button efficient ? 1 Answer