Unityでn秒ごとに処理を実行する
いくつかあったのでまとめ
Time.deltaTimeを用いた方法
using UnityEngine; public class Timer : MonoBehaviour { public float span = 3f; private float currentTime = 0f; void Update () { currentTime += Time.deltaTime; if(currentTime > span){ Debug.LogFormat ("{0}秒経過", span); currentTime = 0f; } } }
コルーチンを用いた方法1(StartCoroutine)
using UnityEngine; public class Timer : MonoBehaviour { public float span = 3f; void Start () { StartCoroutine ("Logging"); } IEnumerator Logging(){ while (true) { yield return new WaitForSeconds (span); Debug.LogFormat ("{0}秒経過", span); } } }
コルーチンを用いた方法2
using UnityEngine; public class Timer : MonoBehaviour { public float span = 3f; IEnumerator Start () { while (true) { yield return new WaitForSeconds (span); Debug.LogFormat ("{0}秒経過", span); } } }
MonoBehaviour.InvokeRepeatingを用いた方法
using UnityEngine; public class Timer : MonoBehaviour { public float span = 3f; void Start () { InvokeRepeating ("Logging", span, span); } void Logging(){ Debug.LogFormat ("{0}秒経過", span); } }
上記すべてでTime.timeScaleの影響を受けるので注意
影響を受けたくない場合はコルーチンでWaitForSecondsRealtimeを使う
ManagerはSingletonで
UnityのSceneで1つしか存在しないスクリプト(主にManager)はSingletonパターンでいいじゃんという話
Singleton パターン - Wikipedia
Managerインスタンスを呼び出すのにGameObject.Find("HogeManager")と毎回書くのがめんどくさいので以下のようなスクリプトにすれば簡単に他クラスからHogeManager.Instanceでインスタンスにアクセスできる。
using UnityEngine; public class HogeManager : MonoBehaviour { public static HogeManager Instance; // Awakeはシーン開始時に呼び出される void Awake () { if (Instance == null) { Instance = this; } else { // シーン内にすでにHogeManagerが存在する場合は自分を削除 Destroy (this); } } }