プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Unity コルーチンを利用したカウントアップ

■Unityのコルーチンを利用したカウントアップ方法
 


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CountUp : MonoBehaviour
{
    // 表示用のカウントアップ
    public Text countText;
    // カウントアップ変数
    private int count;
    // Updateメソッドでコルーチン実行を制御用フラグ
    private bool flg;

    // Start is called before the first frame update
    void Start()
    {
        // 変数初期化
        count = 0;
        flg = false;
    }

    // Update is called once per frame
    void Update()
    {
        // フラグがfalseの場合、コルーチン実行
        if (!flg) {
            StartCoroutine("Count");
        }
    }

    private IEnumerator Count() {
        // フラグをtrueにして次に実行されるコルーチンを止める
        flg = true;

        // 1秒待ってcountを1増やす
        yield return new WaitForSeconds(1.0F);
        count++;

        // 表示用の「countText」にcount変数の値をセット
        countText.text = count.ToString();

        // 上記で1秒待っている状態なので、コルーチンが実行できるようにフラグをfalseに変更
        flg = false;
    }
}