# Creators – Random Pin Placement

This week we worked on random pin placement for our game. We updated the existing PinManager component to randomly (as opposed to regularly) place a number of pins into the scene.

Arrays

An array is a way for a variable to hold more than one value. It’s a a very useful concept in programming; complex programs would be practically impossible without them. In C# arrays are declared as follows:

```     int[] nums = new int;
bool[,] grid = new bool[rows, cols];```

The first line creates a one-dimensional array called nums which has four entries: nums, nums, nums and nums.

The second line creates a two-dimensional array called grid. Note the size in this case depends on the values of the variables rows and cols. The first entry is grid[0,0] and the last is grid[rows – 1, cols – 1]. The total number of locations in this array is rows * cols.

The Algorithm

An ‘algorithm’ is a process or series of rules to follow to accomplish a task. We talked about an algorithm for randomly picking a number of locations on a grid. This algorithm is represented in the flow chart below: The first two steps in this algorithm we determined in the Unity editor. The rest of the algorithm was captured in a method called CalculateRandomGrid:

```   private bool [,] CalculateRandomGrid(int rows, int cols, int num)
{
bool[,] grid = new bool[rows, cols];
int count = 0;

// Until we have have enough items, keep generating new ones
while (count < num)
{
// Pick a random row and column
int row = Random.Range (0, rows);
int col = Random.Range (0, cols);

// See if there's already something there
if (grid [row, col] == false)
{
// If not, mark it as something and increase the
// count of things we've made
grid[row, col] = true;
count++;
}
}

return grid;
}```

Placing the Pins

Once we had determined the random layout, we proceeded to place the pins.  We established a corner to our grid and used code to work out the width of each column and the height of each row. Once we had those, we looped over every position in the random grid and placed a pin at each marked location:

```   void RandomLayout()
{
bool[,] grid = CalculateRandomGrid (NumberOfRows + 1,
NumberOfColumns + 1,
NumberOfPins);
float deltaX = _totalWidth / NumberOfColumns;
float deltaZ = _totalDepth / NumberOfRows;

for (int col = 0; col <= NumberOfColumns; col++)
{
for (int row = 0; row <= NumberOfRows; row++)
{
if (grid [row, col] == true)
{
// Work out location and rotation
Vector3 pos = _corner + new Vector3(deltaX * col,
0.5f,
deltaZ * row);
// Place pin
Instantiate (PinPrefab, pos, Quaternion.identity);
}
}
}
}``` Blender

We also looked a little at Blender and building a pin model. We’ll do more of this next week, so for now we won’t discuss this here. I did promise to share the final Blender model also, but I’ll hold that for next week too. Project

The updated project can be found here.