- Home /
Instantiating prefabs as child of a gameobject
I have a spawner game object which spawns obstacle prefab. I'm trying to make this spawned objects childs of the spawner game object.
Here is my code;
public class ObstacleSpawn : MonoBehaviour
{
public GameObject Obstacle;
void Start()
{
Vector3 center = transform.position;
for (int i = 0; i < 10; i++)
{
Vector3 pos = RandomCircle(center, 1.07f);
Quaternion rot = Quaternion.FromToRotation(Vector3.down, center - pos);
Instantiate(Obstacle, pos, Quaternion.identity);
}
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
pos.z = center.z + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
return pos;
}
void Update()
{
}
}
Answer by GrayLightGames · Nov 03, 2019 at 03:02 PM
Hi @ertunaozderya, Instantiate has an optional parameter for the parent... so you can just Instantiate it like so:
Instantiate(Obstacle, pos, Quaternion.identity, transform);
Transform is actually this.transform, but "this" is implied.
Here are all the overloads for Instantiate:
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
[1]: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Thank you so much but i solved the problem yesterday :)
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Prefab, procedural attachment of child, childCount return 0 1 Answer
Instantiate a Prefab as child 0 Answers
How to Instantiate Prefab as Child of Player OnTriggerEnter 0 Answers
Give prefab a parent 2 Answers