美文网首页
Unity中实现UI渐隐渐显的效果

Unity中实现UI渐隐渐显的效果

作者: ssas_ | 来源:发表于2018-12-25 15:21 被阅读0次

    实现效果:点击按钮,目标UI会逐渐消失,再次点击按钮,UI会逐渐出现。
    具体实现代码如下:

    /// <summary>
    ///          项目名称:
    ///
    ///          脚本作用:UI渐变效果
    ///
    ///          日期:2018-12-25
    ///
    ///          作者:Olivia
    /// </summary>
    
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class UIFadeInFadeOut : MonoBehaviour {
        public float targetAlpha = 1.0f;              
        public float alphaSpeed = 2.0f;
        public Button btn;
    
        private bool depressFlag = false;
        private CanvasGroup canvasGroup;
    
        void Start()
        {
            canvasGroup = this.GetComponent<CanvasGroup>();
            btn.onClick.AddListener(delegate ()
            {
                OnClickBtn();
            });
        }
    
        void Update()
        {
            if(canvasGroup == null)
            {
                return;
            }
                
            if(targetAlpha != canvasGroup.alpha)
            {
                canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetAlpha, alphaSpeed * Time.deltaTime);
                if(Mathf.Abs(targetAlpha - canvasGroup.alpha) <= 0.01f)
                {
                    canvasGroup.alpha = targetAlpha;
                }
            }
        }
    
        /// <summary>
        /// UI出现与隐藏
        /// </summary>
        public void OnClickBtn()
        {
            //出现
            if(depressFlag == true)
            {
                targetAlpha = 1.0f;
                canvasGroup.blocksRaycasts = true;
                depressFlag = false;
            }
            //隐藏
            else
            {
                targetAlpha = 0;
                canvasGroup.blocksRaycasts = false;
                depressFlag = true;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Unity中实现UI渐隐渐显的效果

          本文链接:https://www.haomeiwen.com/subject/kvyflqtx.html