Repeat with for
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 37 of 85.
A for loop runs its lines again and again, counting as it goes:
for (int i = 0; i < 5; i++)
{
Debug.Log("Round " + i);
}The parentheses hold three parts: where the counter starts (int i = 0), the condition to keep going (i < 5) and what happens after each round (i++). This loop runs 5 times, with i at 0, 1, 2, 3 and 4.
You can do math with the counter: i * 2 gives 0, 2, 4, 6 and 8.
PlaceCrate is a method written for you: a named group of lines. PlaceCrate(3); runs them and puts a crate at x = 3. You will write your own methods later in this chapter.
Challenge
MediumPlace 5 crates in a row with a for loop.
- In
Start(), replacePlaceCrate(0);withfor (int i = 0; i < 5; i++)and its braces. - Inside the loop, call
PlaceCrate(i * 2 - 4);, which gives x = -4, -2, 0, 2 and 4.
Press Play: five crates stand in a row, 2 apart. Then Check.
Try it yourself
using UnityEngine;
public class CrateRow : MonoBehaviour
{
void Start()
{
// Place 5 crates: at x = -4, -2, 0, 2 and 4.
PlaceCrate(0);
}
void PlaceCrate(float x)
{
GameObject crate = GameObject.CreatePrimitive(PrimitiveType.Cube);
crate.name = "Crate";
crate.transform.position = new Vector3(x, 0.5f, 0);
crate.GetComponent<Renderer>().material.color = new Color(0.8f, 0.55f, 0.3f);
}
}
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