Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Representing tile based 2D game levels using 2D arrays

Notes:

I. Representing tile based 2D game levels using 2D arrays: [Starts at: 00min:00sec]

Example Code:

using UnityEngine;
public class ArraysDemo : MonoBehaviour {
void Start () {

// Level design using 2d array
/*
int[,] level0 = new int[,]{
{1,1,1,1,1},
{1,1,1,1,1},
{1,0,1,0,1},
{1,0,1,0,1},
{1,0,0,0,1}
};

for (int row = 0; row < level0.GetLength(0); row++) {
for (int col = 0; col < level0.GetLength(1); col++) {
if (level0 [row, col] == 1) {
Debug.Log (string.Format ("Draw brick at {0} and {1}", row, col));
}
}
}
*/

/*
int[,] level1 = new int[,]{
{1,1,1,1,1},
{1,1,1,1,0},
{1,1,1,0,0},
{1,1,0,0,0},
{1,0,0,0,0}
};

for (int row = 0; row < level1.GetLength(0); row++) {
for (int col = 0; col < level1.GetLength(1); col++) {
if (level1 [row, col] == 1) {
Debug.Log (string.Format ("Draw brick at {0} and {1}", row, col));
}
}
}
*/

int[,] level2 = new int[,]{
{1,1,1,1,2},
{1,1,1,2,0},
{1,1,2,0,0},
{1,2,0,0,0},
{2,0,0,0,0}
};

for (int row = 0; row < level2.GetLength(0); row++) {
for (int col = 0; col < level2.GetLength(1); col++) {

/*
if (level2 [row, col] == 1) {
Debug.Log (string.Format ("Draw brick at {0} and {1}", row, col));
}
if (level2 [row, col] == 2) {
Debug.Log (string.Format ("Draw red brick at {0} and {1}", row, col));
}
*/

switch (level2 [row, col]) {
case 1:
Debug.Log (string.Format ("Draw brick at {0} and {1}", row, col));
break;
case 2:
Debug.Log (string.Format ("Draw red brick at {0} and {1}", row, col));
break;
}
}
}

}
}