80 lines
1.4 KiB
C#
80 lines
1.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
public class UIFader : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private CanvasGroup _canvasGroup;
|
|
|
|
[SerializeField]
|
|
private float _duration = 0.5f;
|
|
|
|
private float _timer;
|
|
|
|
private Coroutine _coroutine;
|
|
|
|
private Action _onComplete;
|
|
|
|
public void FadeOut(Action onComplete = null)
|
|
{
|
|
if (_coroutine != null)
|
|
{
|
|
StopCoroutine(_coroutine);
|
|
}
|
|
_onComplete = onComplete;
|
|
_timer = 0f;
|
|
_canvasGroup.alpha = 0f;
|
|
base.gameObject.SetActive(true);
|
|
_coroutine = StartCoroutine(FadeOutCoroutine());
|
|
}
|
|
|
|
public void FadeIn(Action onComplete = null)
|
|
{
|
|
if (_coroutine != null)
|
|
{
|
|
StopCoroutine(_coroutine);
|
|
}
|
|
_onComplete = onComplete;
|
|
_timer = 0f;
|
|
_canvasGroup.alpha = 1f;
|
|
base.gameObject.SetActive(true);
|
|
_coroutine = StartCoroutine(FadeInCoroutine());
|
|
}
|
|
|
|
private IEnumerator FadeOutCoroutine()
|
|
{
|
|
float t = 0f;
|
|
while (t < 1f)
|
|
{
|
|
t = _timer / _duration;
|
|
_canvasGroup.alpha = t;
|
|
_timer += Time.deltaTime;
|
|
yield return null;
|
|
}
|
|
if (_onComplete != null)
|
|
{
|
|
_onComplete();
|
|
}
|
|
_onComplete = null;
|
|
}
|
|
|
|
private IEnumerator FadeInCoroutine()
|
|
{
|
|
float t = 0f;
|
|
while (t < 1f)
|
|
{
|
|
t = _timer / _duration;
|
|
_canvasGroup.alpha = 1f - t;
|
|
_timer += Time.deltaTime;
|
|
yield return null;
|
|
}
|
|
base.gameObject.SetActive(false);
|
|
if (_onComplete != null)
|
|
{
|
|
_onComplete();
|
|
}
|
|
_onComplete = null;
|
|
}
|
|
}
|