Hi,i would like to spawn objects with for loop,so i have an empty object,and that contains 4 more empty objects as children.And i would like to spawn an object at each empty object.I figured if i loop trough them,i could spawn the objects at the four empty objects but i can’t make it work.
void Awake()
{
points = new Vector3[transform.childCount];
for (int i = 0; i < points.Length; i++)
{
cube = Instantiate(prefab, points[i], transform.rotation);
cube.transform.parent = transform;
}
}
In the original code, the array of Vectors is uninitialized, which means they will all be Vector3.zero.
The next post’s code will also have a problem because it adds new children (by parenting them to the same transform) from within the for loop that iterates over all children. This means that for the first child it will make a new child, now you’ll have 5 total. In other words the first loop will never end.
The second block of code in the first post might work but I recommend first copying the Vector3 positions out to a Vector3[ ] array, THEN go and make all the objects, at least as long as they are going to be parented to the same object!
You could also parent each object to the child it was spawned off, which gets you out of the problem of changing the number of children in that transform during the loop.
Getting this stuff right can be tricky, but it’s really rewarding when you get it all working and also understand the reasons why it’s all doing what it is doing.
Mmm, you’re right Kurt, thanks for pointing that out. I I meant to parent it to the child’s transform (I think that was the OP original intention too).
I already corrected the code and should work well now.