Menu
CoddyTech

Arrays

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 41 of 85.

An array holds many values of one type in a row. Its type has square brackets after it, and its values go between braces:

int[] scores = { 10, 25, 7 };

Each value has an index, its place in the row, and counting starts at 0: scores[0] is 10, scores[1] is 25 and scores[2] is 7. scores.Length is how many values there are, 3 here. Asking for scores[3] stops the script with an IndexOutOfRangeException: there is no fourth value.

A for loop up to Length visits every value, whatever the array holds:

for (int i = 0; i < scores.Length; i++)
{
    Debug.Log("Score " + i + ": " + scores[i]);
}

When you do not need the index, foreach is shorter: foreach (int s in scores) { Debug.Log(s); } runs once for every value, in order.

challenge icon

Challenge

Medium

Make the skyline 7 towers long with an array and a loop.

  1. Add 6f and 2f to the end of heights: { 2f, 5f, 3f, 1f, 4f, 6f, 2f }.
  2. Replace the PlaceTower line with for (int i = 0; i < heights.Length; i++).
  3. Inside it, call PlaceTower(i * 1.5f - 4.5f, heights[i]);.

Press Play: seven towers of different heights stand in a row. Then Check.

Try it yourself

using UnityEngine;

public class Skyline : MonoBehaviour
{
    void Start()
    {
        float[] heights = { 2f, 5f, 3f, 1f, 4f };

        // Place one tower for every height.
        PlaceTower(-4.5f, heights[0]);
    }

    void PlaceTower(float x, float height)
    {
        GameObject tower = GameObject.CreatePrimitive(PrimitiveType.Cube);
        tower.name = "Tower";
        tower.transform.position = new Vector3(x, height / 2, 0);
        tower.transform.localScale = new Vector3(1, height, 1);
        tower.GetComponent<Renderer>().material.color = new Color(0.35f, 0.45f, 0.7f);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground