キューバに行ってみたい

ゲーム開発とかWeb開発とか

[Unity] n秒ごとにイベントを発火する script を書いてみる

Version unity 2020.3.27.f1 で動作検証を行っています。

特定の周期でテキストを点滅させたいなどあるかと思います。

今回はそのような n秒ごとに特定のイベントを実行したい時の実装例を紹介します。

0.5秒ごとにテキストを点滅させてみる

例ではテキスト (TextMeshPro) を 0.5秒ごとに点滅させます。

こんな感じです。

以下の script を text にアタッチします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;


public class BlinkingTextController : MonoBehaviour
{
    private TextMeshProUGUI t;
    private float alpha = 1.0f;
    private float elapsedTime = 0f;

    private void Start()
    {
        this.t = this.gameObject.GetComponent<TextMeshProUGUI>();
    }

    private void Update()
    {
        Blink();
    }

    private void Blink()
    {

        this.elapsedTime += Time.deltaTime;
        if (this.elapsedTime > 0.5f)
        {
            this.alpha = this.alpha == 1.0f ? 0.0f : 1.0f;
            this.t.color = new Color(255, 255, 255, alpha);
            this.elapsedTime = 0.0f;
        }
    }
}

elapsedTime に Time.deltaTime を加算し前フレームからの経過時間を積み重ねます。

elapsedTime (経過時間) が 0.5f秒経過するごとに text の alpha値を変更して点滅させています。

今回はテキストを点滅させましたが、他の処理でも応用することができるかと思います。

簡単ですが以上です。