Files
beyond/Assets/Scripts/UI/UIImageFader.cs

80 lines
1.9 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UIImageFader : MonoBehaviour
{
[SerializeField] private Image targetImage;
[Header("Fade Settings")]
public float fadeInDuration = 1f;
public float fadeOutDuration = 1f;
public float fadeOutDelay = 0f;
private bool isFading = false;
private void Awake()
{
if (targetImage == null)
{
targetImage = GetComponent<Image>();
}
// Set initial alpha to 0 (completely transparent)
SetAlpha(0f);
}
// Method to start the fade process
public void StartFade()
{
if (!isFading && gameObject.activeInHierarchy && enabled)
{
StartCoroutine(FadeRoutine());
}
}
private IEnumerator FadeRoutine()
{
isFading = true;
// Start Fade In
yield return StartCoroutine(Fade(0f, 1f, fadeInDuration));
// Optional delay before fade out
yield return new WaitForSeconds(fadeOutDelay);
// Start Fade Out
yield return StartCoroutine(Fade(1f, 0f, fadeOutDuration));
isFading = false;
}
private IEnumerator Fade(float startAlpha, float endAlpha, float duration)
{
float elapsedTime = 0f;
Color color = targetImage.color;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float alpha = Mathf.Lerp(startAlpha, endAlpha, elapsedTime / duration);
SetAlpha(alpha);
yield return null;
}
// Ensure the final alpha is set
SetAlpha(endAlpha);
}
// Method to set alpha of the image
private void SetAlpha(float alpha)
{
if (targetImage != null)
{
Color color = targetImage.color;
color.a = alpha;
targetImage.color = color;
}
}
}