04 / 11 · 4 min
Basics
Branch and repeat
your project so far
Last reading lesson. The nested for loop here becomes the block grid in lesson 08.
Last C# lesson. Two structures — a fork and a repeat — cover almost all gameplay code.
animated diagram
if picks one road. for runs the same block a fixed number of times.
Deciding
C# script
if (hp <= 0) Die();
else if (hp < 30) PlayLowHealthSound();
else /* fine */ ;
// combine conditions
if (isGrounded && Input.GetKeyDown(KeyCode.Space)) Jump(); // && = and
if (isStunned || isDead) return;Repeating
C# script
// run 5 times, i = 0,1,2,3,4
for (int i = 0; i < 5; i++)
Debug.Log("cube " + i);
// grid: 4 x 4 = 16 times
for (int x = 0; x < 4; x++)
for (int z = 0; z < 4; z++)
Debug.Log(x + "," + z);Lists — many things at once
needs: using System.Collections.Generic;
using System.Collections.Generic;
public List<GameObject> characters = new List<GameObject>();
void Start()
{
characters.Add(knight); // add
Debug.Log(characters.Count);
GameObject first = characters[0]; // index starts at 0
foreach (GameObject c in characters) // walk through all
c.SetActive(false);
}Indexes start at 0, so a list of 3 has indexes 0, 1 and 2.
Use for when you need the number i; use foreach when you just need each item.
A public List shows up in the Inspector as a drag-and-drop slot list — that is how the character swap will work.