UI弹出动画

发布于:2025-08-30 ⋅ 阅读:(12) ⋅ 点赞:(0)

简介的UI弹出动画

使用方式很简单 挂载到需要弹出的目标 即可

using UnityEngine;
using DG.Tweening;
using Unity.VisualScripting;


    /// <summary>
    /// 简洁的UI动画脚本
    /// 直接挂载到UI组件上,调用Play()播放缩放弹出动画
    /// </summary>
    public class UIAnimation : MonoBehaviour
    {
        [Header("动画设置")]
        [SerializeField] private float duration = 0.5f;
        [SerializeField] private Ease easeType = Ease.OutBack;

        private RectTransform rectTransform;
        private Vector3 originalScale;

        private void Start()
        {


        }
        private void OnEnable()
        {
            rectTransform = GetComponent<RectTransform>();
            if (rectTransform != null)
            {
                originalScale = rectTransform.localScale;
                // 初始设为0缩放
                rectTransform.localScale = Vector3.zero;
            }
            Play();
        }
        /// <summary>
        /// 播放弹出动画
        /// </summary>
        public void Play()
        {
            if (rectTransform != null)
            {
                gameObject.SetActive(true);
                rectTransform.localScale = Vector3.zero;
                rectTransform.DOScale(originalScale, duration).SetEase(easeType);
            }
        }

        /// <summary>
        /// 隐藏UI
        /// </summary>
        public void Hide()
        {
            if (rectTransform != null)
            {
                rectTransform.DOScale(Vector3.zero, duration * 0.5f)
                    .SetEase(Ease.InBack)
                    .OnComplete(() => gameObject.SetActive(false));
            }
        }

        private void OnDestroy()
        {
            rectTransform?.DOKill();
        }
    
}