Spawning object to array's child position.

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;
        }
    }

I think the problem is that you’re creating just one vector3. The [ ] box is not well used in the case of the vector afaik.
Try it like this instead:

    void Awake()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            cube = Instantiate(prefab, transform.GetChild(i).position, transform.rotation);
            cube.transform.parent = transform.GetChild(i);
        }
    }

I think you can also write it more readable using something like this:

    void Awake()
    {
        foreach (Transform child in transform)
        {
          Instantiate(prefab, Vector3.zero, Quaternion.identity, child);
        }
    }

I think that if your prefab has zero rotations and position, you can just use Instantiate(prefab, transform); instead.

1 Like

Thank you,i’m going to try it out!

There’s a couple of things here to watch out for.

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.

1 Like

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.

1 Like