Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Nested loops, Scanning or Processing 2d tile map

Notes:

I. How for loop works: [Starts at:00min:47sec]
II. C# nested loops : [Starts at:04min:21sec]
III. Scanning 2D tile map using nested loops: [Starts at:17min:01sec]
IV. Creating repeated sequence with %(Modulus) and / operators: [Starts at:21min:19sec]
V. Processing 2D tile map using % and / operators: [Starts at:27min:09sec]

I. How for loop works: [Starts at:00min:47sec]

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
for (int i = 0; i < 2; i++)
{
Debug.Log ("Hello Unity");
}
}
}

II. C# nested loops : [Starts at:04min:21sec]
If required we can nest loops.
i.e. we can placing one loop inside another loop.

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
int n = 2;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Debug.Log ("Hello Unity"); // executes n * n times
}
}
// And
int m = 2;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Debug.Log ("Hello Unity"); // executes m * n times
}
}
}
}

III. Scanning 2D tile map using nested loops: [Starts at:17min:01sec]

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
// loop through rows and cols of 2d tile map
for (int row = 0; row < 2; row++)
{
for (int col = 0; col < 2; col++)
{
Debug.Log (string.Format("row = {0} and col = {1}", row, col));
}
}
}
}

IV. Creating repeated sequence with %(Modulus) and / operators: [Starts at:21min:19sec]

Note:
Modulus(%) is used to lock the result, or get repeated sequence
Ex:
0 % 2 = 0
1 % 2 = 1

2 % 2 = 0
3 % 2 = 1

4 % 2 = 0
5 % 2 = 1

6 % 2 = 0
7 % 2 = 1

8 % 2 = 0
9 % 2 = 1

Division(/) is used to get same number repeatedly : (int/int=int)
Ex:
0 / 2 = 0
1 / 2 = 0

2 / 2 = 1
3 / 2 = 1

4 / 2 = 2
5 / 2 = 2

6 / 2 = 3
7 / 2 = 3

8 / 2 = 4
9 / 2 = 4

V. Processing 2D tile map using % and / operators: [Starts at:27min:09sec]

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
// loop through rows and cols of 2d tile map
// column wise i.e horizontally
int numRows = 2;
int numCols = 2;
int tile = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
int r = tile / numCols; // get rows 0 0 1 1
int c = tile % numCols; // get cols 0 1 0 1
Debug.Log (string.Format ("row = {0} and col = {1}", r, c));
tile++;
}
}
}
}