- Home /
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
Answer by graviton · Apr 09, 2015 at 10:35 PM
I got the answer to my question here
http://forum.unity3d.com/threads/rearranging-pre-existing-objcets-into-a-grid.316816/
Answer by Catfang007 · Apr 07, 2015 at 12:32 AM
If you use a Grid Layout Group script on your empty GameObject, this should happen automagically.
Thanks Catfang007
I don't have Unity 4.6+, but I'll try this way when I get a newer version of Unity