- 增加 Image 空引用保护 - 处理 duration 小于等于 0 的边界情况 - 动画开始前调用 DOKill 避免冲突 - 使用 DOFade 替代 DOBlendableColor,行为更明确
83 lines
2.3 KiB
C#
83 lines
2.3 KiB
C#
using System.Collections;
|
|
using DG.Tweening;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace AibisDream.Framework
|
|
{
|
|
public static class FadeKit
|
|
{
|
|
public static IEnumerator FadeInAsync(this Image image, float duration, bool useUnscaledTime = false)
|
|
{
|
|
var tweener = StartFade(image, 1f, duration, useUnscaledTime);
|
|
if (tweener != null)
|
|
{
|
|
yield return tweener.WaitForCompletion();
|
|
}
|
|
}
|
|
|
|
public static void FadeIn(this Image image, float duration)
|
|
{
|
|
StartFade(image, 1f, duration, false);
|
|
}
|
|
|
|
public static IEnumerator FadeOutAsync(this Image image, float duration, bool useUnscaledTime = false)
|
|
{
|
|
var completed = false;
|
|
var tweener = StartFade(image, 0f, duration, useUnscaledTime);
|
|
if (tweener == null)
|
|
{
|
|
image?.gameObject.SetActive(false);
|
|
yield break;
|
|
}
|
|
|
|
tweener.OnComplete(() => completed = true);
|
|
yield return tweener.WaitForCompletion();
|
|
if (completed && image != null)
|
|
{
|
|
image.gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
public static void FadeOut(this Image image, float duration)
|
|
{
|
|
var tweener = StartFade(image, 0f, duration, false);
|
|
if (tweener == null)
|
|
{
|
|
image?.gameObject.SetActive(false);
|
|
return;
|
|
}
|
|
|
|
tweener.OnComplete(() =>
|
|
{
|
|
if (image != null)
|
|
{
|
|
image.gameObject.SetActive(false);
|
|
}
|
|
});
|
|
}
|
|
|
|
private static Tweener StartFade(Image image, float targetAlpha, float duration, bool useUnscaledTime)
|
|
{
|
|
if (image == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
image.DOKill(false);
|
|
image.gameObject.SetActive(true);
|
|
|
|
duration = Mathf.Max(0f, duration);
|
|
if (duration <= 0f)
|
|
{
|
|
var color = image.color;
|
|
color.a = targetAlpha;
|
|
image.color = color;
|
|
return null;
|
|
}
|
|
|
|
return image.DOFade(targetAlpha, duration).SetUpdate(useUnscaledTime);
|
|
}
|
|
}
|
|
}
|