- Home /
spawn prefabs as children of another game object
i am making an endless runner where the player runs on top of a cylindrical - continuously rotating world. now i need to spawn obstacles (prefabs) on the cylinder and make them(prefabs) have the same motion as the cylinder... im done with the spawning but do not know how to place the spawned prefab as a child of another prefab(the level)so that they move along with the level. please help.
Answer by ZenithCode · Nov 01, 2012 at 01:27 PM
Ok so you need to set the parent object after you instantiate the new object as follows.
Gameobject GO = Instantiate(myPrefab);
myPrefab.trasnform.parent = ParentGameObject;
myPrefab is the one you want to instantiate
hi, thanks for the help.... i tried to use it but got this error :
"Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption."
this is my code:
var brick : Transform;
function Start ()
{
Instantiate(brick, Vector3 (0, 0, 10), Quaternion.identity);
brick.transform.parent = transform.the_world;
}
pls help...
I don't know what transform.the_world is but this solution is wrong. With this code myPrefab.trasnform.parent = ParentGameObject; you are trying to set a GameObject where a link to a Transform is needed.
Plus, your code is totally wrong too. Look at my solution.
You're wrong, you should do
Gameobject GO = Instantiate(myPrefab);
GO.transform.parent = ParentGameObject;
You can't set a prefab parent, only a gameObject
Answer by valyard · Nov 01, 2012 at 01:52 PM
To attach a GameObject as a child of another GameObject you need to set its transform.parent to that other GameObject's transform. For example if you want to attach a new prefab copy to this GameObject you would write something like this:
GameObject obj = Instantiate(Prefab) as GameObject;
obj.transform.parent = transform;
Update: Changed your code so it should work. Provided that you want the new brick copy to be attached to current GameObject.
var brick : GameObject;
function Start () {
var object = Instantiate(brick, Vector3 (0, 0, 10), Quaternion.identity);
object.transform.parent = transform;
}
whoever you are, you ARE A$$anonymous$$AZING! been trying for like EVER to get it!
Your answer
![](https://koobas.hobune.stream/wayback/20220613083203im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Make a simple tree 1 Answer
Give prefab a parent 2 Answers
spawning object as child of other:error 2 Answers
Child Animation synced with Parrent objects Animation 0 Answers
Instantiate a Prefab as child 0 Answers