Rearranging pre-existing objcets into a grid

This really should be simple, but I can’t seem to rap my head around the logic

I’m trying to create a grid using objects that already exist in the world. I can create a grid as the objects are instantiated just fine, but can’t seem to do it with pre-existing objects

In my Hierarchy, I have an EmptyGameObject named “myEmptyGameObject” and it has 4 Child Objects

Here’s my code

//Re-arranges pre-existing objects into a Row, Column or Grid

using UnityEngine;
using System.Collections;

public class listToGridTest : MonoBehaviour
{
   
    public float newY;
    public float newX;
    bool finishedSpawning;
   
    void Start()
    {
        StartCoroutine(SortCoroutine());
    }
   
    // Update is called once per frame
    void Update ()
    {
        if (!finishedSpawning)
            return;
    }


    private IEnumerator SortCoroutine()
    {
        finishedSpawning = false;
       
        Transform otherGameObject = GameObject.Find("myEmptyGameObject").GetComponentInChildren<Transform>();
       
        int grids = otherGameObject.childCount;
        for (int i = 0 ; i <= grids - 1; i++)
        {
            for (int y = 2; y > 0; y--)
            {
                newY += y*2;
                otherGameObject.GetChild(i).transform.position = new Vector3(newX, newY, 1);
               
                for (int x = 0; x < 2; x++)
                {
                    newX += x*2;
                    otherGameObject.GetChild(i).transform.position = new Vector3(newX, newY, 1);
                }
                yield return new WaitForSeconds(1f);
            }
        }
       
        finishedSpawning = true;
    }

}

I seem to have hit a mental block

I’m not entirely sure about what’s going on because of your rather undescriptive naming scheme (“other game object” and “my empty game object”), but I believe you are trying to sort the four children of myEmptyGameObject, yes?

You get the Transform of one of the children of the myEmptyGameObject GameObject, which is the parent object holding the four children you intent to re-arrange. Then, you try to get a child from that child, instead of getting the children of myEmptyGameObject. What you should be doing instead is using the transform of myEmptyGameObject directly, and then moving the transforms of its children. (GameObject.Find(“myEmptyGameObject”).transform)

Also, you’re positioning the same object many times over. In the outer most loop, you pick the child object you want. Then, you move that object twice in the y loop, and in that y loop you move it twice in the x loop again; that’s a lot of needless moving about. I see there’s a WaitForSeconds so maybe you’re animating the movement into the grid, but only after doing the x loop, so the movement in that loop isn’t being displayed.

1 Like