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
MediumMake the skyline 7 towers long with an array and a loop.
- Add
6fand2fto the end ofheights:{ 2f, 5f, 3f, 1f, 4f, 6f, 2f }. - Replace the
PlaceTowerline withfor (int i = 0; i < heights.Length; i++). - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector7Loops and Methods
Repeat with forLoops Inside LoopsWrite a MethodMethods That AnswerArraysRecap: Staircase2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground