ゲームを作っていて特定のGameObjectの数を数えたい時がある。
例えば、敵キャラを数えておいて全員倒されたらゲームクリア!!のように設定したい場合。
そういう時は以下のコードを使うと良い。
public class GameManager : MonoBehaviour { GameObject[] tagObjects; float timer = 0.0f; float interval = 3.0f; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { timer += Time.deltaTime; if (timer > interval) { Check("Enemy"); timer = 0; } } void Check(string tagname) { tagObjects = GameObject.FindGameObjectsWithTag(tagname); if (tagObjects.Length == 0) { SceneManager.LoadScene("GameClear"); } } }
時間のインターバルはいらないかもしれないが、アップデートの中で頻繁に呼び出すものなので、インターバルを広めにしておいた方が負荷が下がる。