Unity Push通知のようなフェードイン、フェードアウトして自動で消えるようなオブジェクト作成例

使い方はなんかボタン押したときにInstantiateで生成して、OnStartを実行する。

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

/**
 * デバッグ用プッシュ通知的な通知をcanvasに出す
 */
[RequireComponent(typeof(CanvasGroup))]
public class PushNotificationUI : MonoBehaviour
{
    [SerializeField] private Text message;
    private CanvasGroup group;
    private float duration;
    private float elapsed;

    public void OnStart(string text)
    {
        group = GetComponent<CanvasGroup>();
        duration = 0.3f;
        message.text = text;

        StartCoroutine(Action());
    }

    private IEnumerator Action() {
        yield return FadeIn();
        yield return new WaitForSeconds(0.7f);
        yield return FadeOut();

        Destroy(this.gameObject);
    }
    private IEnumerator FadeIn()
    {
        elapsed = 0f;
        while (true) {
            elapsed += Time.deltaTime;
            var per = Mathf.Min(elapsed / duration, 1.0f);
            group.alpha = per;
            if (per >= 1.0f) { break; }
            yield return null;
        }
        group.alpha = 1f;
    }
    private IEnumerator FadeOut()
    {
        elapsed = 0f;
        while (true) {
            elapsed += Time.deltaTime;
            var per = Mathf.Min(elapsed / duration, 1.0f);
            group.alpha = 1.0f - per;
            if (per >= 1.0f) { break; }
            yield return null;
        }
        group.alpha = 0f;
    }
}