04 / 11 · 4 分钟
基础
分支与循环
到目前为止的项目
最后一节纯阅读课。这里的嵌套 for 循环,到第 08 课会变成方块网格。
最后一节 C# 课。只要有分支和循环这两个结构,几乎全部的 gameplay 代码都能写出来。
动态图解
if 只挑一条路走;for 把同一段代码按事先定好的次数重复跑。
按条件分支
C# 脚本
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;重复执行
C# 脚本
// 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);List —— 一次管一堆东西
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);
}索引从 0 开始数,所以 3 个元素的 List,索引是 0、1、2。
需要 i 这个数字就用 for,只要拿到每个元素就用 foreach。
public 的 List 会在 Inspector 里显示成一排可拖放的槽位 —— 换角色就是靠这个机制做的。