Unity实现UI渐隐渐显效果

本文实例为大家分享了Unity实现UI渐隐渐显效果的具体代码,供大家参考,具体内容如下

1、在UI对象上添加组件:CanvasGroup;

2、在对象上添加脚本:UI_FadeInFadeOut 脚本;

脚本信息:

(Blocks Raycasts=true可以交互;Blocks Raycasts=false无法交互)

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

/// <summary>

/// UI的渐入渐出

/// </summary>

public class UI_FadeInFadeOut : MonoBehaviour {

private float UI_Alpha = 1; //初始化时让UI显示

public float alphaSpeed = 2f; //渐隐渐显的速度

private CanvasGroup canvasGroup;

// Use this for initialization

void Start () {

canvasGroup = this.GetComponent<CanvasGroup>();

}

// Update is called once per frame

void Update () {

if (canvasGroup == null)

{

return;

}

if (UI_Alpha != canvasGroup.alpha)

{

canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, UI_Alpha, alphaSpeed * Time.deltaTime);

if (Mathf.Abs(UI_Alpha - canvasGroup.alpha) <= 0.01f)

{

canvasGroup.alpha = UI_Alpha;

}

}

}

public void UI_FadeIn_Event()

{

UI_Alpha = 1;

canvasGroup.blocksRaycasts = true; //可以和该对象交互

}

public void UI_FadeOut_Event()

{

UI_Alpha = 0;

canvasGroup.blocksRaycasts = false; //不可以和该对象交互

}

}

3、需要显示时,添加  UI_FadeIn_Event()  事件;

4、需要隐藏时,添加  UI_FadeOut_Event()  事件;

5、注意:父物体隐藏和显示时,子物体同样也隐藏和显示。

以上是 Unity实现UI渐隐渐显效果 的全部内容, 来源链接: utcz.com/z/355755.html

回到顶部