04 / 11 · 4 分
基礎
分岐と繰り返し
ここまでのプロジェクト
最後の読解レッスン。ここの二重 for ループはレッスン 08 でブロックの格子になります。
最後の C# レッスンです。分岐と繰り返しの二つの構造だけで、ゲームプレイのコードはほぼすべて書けます。
アニメーション図
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 に、ドラッグ&ドロップ用の枠一覧として並びます——キャラクターの差し替えはこの仕組みで動きます。