- Home /
Question by
landon912 · Oct 13, 2012 at 10:19 PM ·
instantiateparentingspawnpointschild-to-gameobject
Instatiate as a child of a GameObject
How can you instaite a game object as a child of a game object(not the one the script is attached to). I have it where a grenade spawns in your hand, but i need to to be parented to the player. I am using an empty as a spawner if that makes a difference. Thanks in advance :)
Comment
Best Answer
Answer by aldonaletto · Oct 13, 2012 at 10:26 PM
Simple: get a reference to the new object and use it to set its parent property:
var grenadePrefab: GameObject;
var player: Transform; // drag the player here in the Inspector
...
var grenade: GameObject = Instantiate(grenadePrefab, ...);
grenade.transform.parent = player; // child to the player object
The actual code depends on the prefab type - for a Transform prefab, it should be:
var grenadePrefab: GameObject;
var player: Transform; // drag the player here in the Inspector
...
var grenade: Transform = Instantiate(grenadePrefab, ...);
grenade.parent = player; // child to the player object
You could also find the player at Start with FindWithTag("Player"), or get the root transform:
var player: Transform;
function Start(){
player = transform.root;
}
...
Your answer
![](https://koobas.hobune.stream/wayback/20220613082307im_/https://answers.unity.com/themes/thub/images/avi.jpg)