- Home /
Instantiate an object as a child of the gameobject's parent
I have an asteroid attached to an empty game object. When the asteroid is destroyed I want to instantiate 2 small asteroids as children of the empty game object.
So from a script attached to the original asteroid I need to instantiate objects as children of the GameObject that the asteroid is a child of via script.
What is the best way to go about this?
Consider an alternate solution. Rather than instantiate the two smaller objects, create all three (one large asteroid and two smaller) as part of the original prefab. Have the two smaller disabled. When the asteroid needs to split, just disable the larger asteroid and disable the the smaller one.
Something like that might work but I'm already looking at having 500+ asteroids loaded at any one time and I'm afraid of a performance hit by doing things like this.
Answer by supernat · Feb 08, 2014 at 07:24 AM
If you are calling Destroy(GameObject) on the parent asteroid, I believe that won't be destroyed until end of frame, and so if you add 2 child objects at the same time, it may appear to work (parent is still valid) but then destroy parent and children end of frame. If you just want to Instantiate two asteroids that start at the same location and have similar velocity (though you would need to change it so the two objects diverge), you would just call Instantiate(prefab, transform.position, transform.rotation); If you want to parent the two, be sure you don't destroy the parent, you could disable its renderer or something, and call like this:
GameObject child = Instantiate(prefab, transform.position, transform.rotation);
child.transform.parent = transform.parent;
Edit: I missed that you wanted to parent the asteroid's parent, so ignore most of this. You can indeed destroy the asteroid if parenting to its parent. I updated the parent line above.
Answer by Griffo · Feb 08, 2014 at 07:25 AM
var asteroid : transform;
private var rock : transform;
function Update(){
if(when you need a asteroid){
Asteroid();
}
}
function Asteroid(){
rock = Instantiate(asteroid, transform.position, Quaternion.identity);
rock.parent = transform.root;
}
Your answer
Follow this Question
Related Questions
How to make an Instantiated prefab a Child of a gameobject that already exists in the hierarchy 3 Answers
Insantiate object to parent without changing scale? 0 Answers
Are my bounds right world position in this case ? 1 Answer
How to make multiple gameobjects child of one and the same transform (SCRIPT) 2 Answers
Create Clones as children in loops? 1 Answer