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

2018-12-25  本文已影响0人  ssas_

实现效果:点击按钮,目标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;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读