⭐Unity 控制任意UI的渐隐渐显

使用脚本之前先给要控制的UI加上CanvasGroup组件

解释:

  • 这个脚本使用协程来逐渐改变CanvasGroupalpha值,从而实现渐隐和渐显的效果。

  • Mathf.Lerp函数用于在指定的时间内平滑地从当前透明度过渡到目标透明度。

  • 通过调用FadeInFadeOut方法,你可以在任何时候启动渐显或渐隐效果。

  • 添加了一个currentFadeCoroutine变量来跟踪当前活跃的协程。

  • 在启动新的渐显或渐隐前,检查并停止已有的协程。

  • 在协程中,如果alpha值已经达到目标值(考虑到浮点数精度),则提前结束循环,避免不必要的计算。

  • 渐变结束时确保alpha值精确设置为目标值,并清除协程引用,确保系统资源得到释放。

using System.Collections;
using UnityEngine;

public class FadeCanvasGroup : MonoBehaviour
{
    public CanvasGroup canvasGroup; // 通过Inspector分配
    public float fadeInDuration = 2.0f; // 渐显持续时间
    public float fadeOutDuration = 2.0f; // 渐隐持续时间
    private Coroutine currentFadeCoroutine; // 当前运行的协程

    void Start()
    {
        // 开始时渐显
        FadeIn();
    }

    public void FadeIn()
    {
        if (currentFadeCoroutine != null) StopCoroutine(currentFadeCoroutine);
        currentFadeCoroutine = StartCoroutine(FadeCanvasGroupRoutine(canvasGroup, canvasGroup.alpha, 1, fadeInDuration));
    }

    public void FadeOut()
    {
        if (currentFadeCoroutine != null) StopCoroutine(currentFadeCoroutine);
        currentFadeCoroutine = StartCoroutine(FadeCanvasGroupRoutine(canvasGroup, canvasGroup.alpha, 0, fadeOutDuration));
    }

    private IEnumerator FadeCanvasGroupRoutine(CanvasGroup cg, float start, float end, float duration)
    {
        float counter = 0f;
        while (counter < duration)
        {
            counter += Time.deltaTime;
            cg.alpha = Mathf.Lerp(start, end, counter / duration);

            // 优化:如果已达到目标透明度,提前终止协程
            if (Mathf.Approximately(cg.alpha, end)) break;

            yield return null; // 等待一帧
        }
        // 确保最终alpha值精确设置
        cg.alpha = end;
        currentFadeCoroutine = null; // 清除协程引用
    }
}

感谢大家的观看,您的点赞和关注是我最大的动力

不定时更新知识点和干货呦~

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值