兵舎の実装【UnityでRTSを作る 8】
今回は前回の記事に引き続き、拠点の実装をします。
今回の拠点は「兵舎」です。
兵舎の実装
CubeKunWarsでは兵舎はユニットをスポーンさせるオブジェクトです。
モデル
兵舎のモデルを用意しました。
キューブ君をかたどっています。
コールバックの追加
前回の記事のBasePoint.csにチーム変更時に呼ばれるコールバックを追加します。
BasePoint.cs
public Team Team { get { return _Team; } set { _Team = value; gameObject.SetLayer(value.ToString()); switch (value) { case Team.Independent: SetColor(Color.white); break; case Team.Ally: SetColor(allyColor); break; case Team.Enemy: SetColor(enemyColor); break; } OnTeamChanged();//Add } } [SerializeField] private Team _Team = Team.Ally; protected virtual void OnTeamChanged () { }
これは兵舎からのキューブ君のスポーンの開始/停止をする際に使います。
スポーン
ここでBarrack.csを作成します。
prefabのCubeKunを一定間隔でスポーンさせ続けます。
Barrack.cs
public class Barrack : BasePoint { public CubeKun prefab; public float time = 5; private Coroutine spawnCoroutine = null; public void SpawnStart () { if (spawnCoroutine == null) spawnCoroutine = StartCoroutine(SpawnCoroutine()); } public void SpawnStop () { if (spawnCoroutine != null) StopCoroutine(spawnCoroutine); } private IEnumerator SpawnCoroutine () { while (true) { Spawn(prefab); yield return new WaitForSeconds(time); } } public CubeKun Spawn (CubeKun prefab) { if (!prefab) throw new ArgumentNullException("prefab"); var ins = Instantiate(prefab,transform.position,transform.rotation); ins.Team = Team; return ins; } protected override void OnTeamChanged () { switch (Team) { case Team.Independent: SpawnStop(); break; case Team.Ally: case Team.Enemy: SpawnStart(); break; } } }
動画