masked雑記

IT関連の記事を書く

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を使う