- Home /
Instantiate prefab as child at a transform? (Javascript/Uniyscript)
I am having a problem with Instantiating a prefab at a transform location. I asked a similar question yesterday about how to Instantiate prefab at a transform but the answer I got seems to require me to give the location of spawn with Vector3 and Quaternion. I am unsure on how to get these to for local space as I don't want it to spawn somewhere random in the world. Yesterdays Question
Current script:
var Weapon1 = Instantiate(GunType, Weapon1Spawn.transform.position, Weapon1Spawn.transform.rotation, Weapon1Spawn);
Instantiating with a parent should use local space you don't need to specify a position;
Instantiate (prefab, parent.transform); //Should work
Something to point out is that parent instantiation was only introduced in Unity 5.4, so check that your version of Unity supports it.
Yeah I can't use it "$$anonymous$$ Identifier "parent"" Is there another way?
If you want it at weapon1Spawn, just use that: Weapon1 = Instantiate(GunType, Weapon1Spawn.transform);
Which is the same as dragging it from your prefabs onto "Weapon1Spawn" in the editor.
If you want to make 100% sure it's straight and aligned (it should be) you can then do(might be slightly different in UnityScript):
weapon1.transform.localPosition = new Vector3(0,0,0);
weapon1.transform.localRotation = Quaternion.identity;
Getting this error using that: http://image.prntscr.com/image/437e04d5f7004f89a604b9078cf63671.jpeg
And you are using at least Unity 5.4? This stuff was introduced very recently, and so if you are using an older version of Unity you will have to set it afterwards.
Answer by txzeenath · Oct 06, 2016 at 01:07 PM
You can also just set the parent manually after instantiating:
Weapon1.transform.parent = Weapon1Spawn.transform;
(I believe you can also use Weapon1.transform.SetParent)
Answer by KreeperGaming · Oct 07, 2016 at 12:27 AM
I'm no expert, but maybe just start it non-active in that transform, and then when called, just activate it.
That is what I do for most of my projects.
If I was using 1 gun type I wouldn't need any kind of instantiation but I am making it so it spawns prefab that is set as "GunType"