Creating a grid of objects

Here’s some stripped down code I use to create a grid of objects in Unity. I’ve used this setup in my Android game Block Blaze when the level is initialised. It’s attached to a Generator object, which also has some other functionality like determining what type of object is created, whether an object needs to be regenerated if its destroyed, what object types are neighbouring, etc.,

public GameObject sampleObj;
public GameObject[,] array = new GameObject[5,4];

private int columns = 4,rows = 5;
private float Xpos = 2.0f;
private float Xoffset = 2.0f;
private float Ypos = 1.0f;
private float Yoffset = 2.0f;

void Start ()
for (int j = 0; j < rows; ++j)
for (int i = 0; i < columns; ++i)
if(array[j,i] == null)
{ = j + " " + i;
array[j,i] = (GameObject) Instantiate (sampleObj, new Vector3(Xpos * (Xoffset * i),Ypos * (Yoffset * i),0), Quaternion.identity);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.