老规矩,先介绍一下Unity的科普小知识:
- using UnityEngine;
-
- public class AutoHide : MonoBehaviour
- {
- public float alphaSpeed = 1f; //渐隐渐显的速度
- private float m_UIAlpha = 1; //初始化时让UI显示
- private CanvasGroup m_CanvasGroup;
- // Use this for initialization
- void Start()
- {
- m_CanvasGroup = this.GetComponent
(); - }
-
- // Update is called once per frame
- void Update()
- {
- if (m_CanvasGroup == null) return;
-
- if (m_UIAlpha != m_CanvasGroup.alpha)
- {
- m_CanvasGroup.alpha = Mathf.Lerp(m_CanvasGroup.alpha, m_UIAlpha, alphaSpeed * Time.deltaTime);
-
- GetComponent
().SetAllSceneModelAlpha(m_CanvasGroup.alpha); -
- if (Mathf.Abs(m_UIAlpha - m_CanvasGroup.alpha) <= 0.01f)
- {
- m_CanvasGroup.alpha = m_UIAlpha;
- }
- }
- }
-
- ///
- /// 显示
- ///
- public void UIFadeInEvent()
- {
- m_UIAlpha = 1;
- if (m_CanvasGroup != null)
- {
- m_CanvasGroup.blocksRaycasts = true; //可以和该对象交互
- }
- }
-
- ///
- /// 隐藏
- ///
- public void UIFadeOutEvent()
- {
- m_UIAlpha = 0;
- if (m_CanvasGroup != null)
- {
- m_CanvasGroup.blocksRaycasts = false; //不可以和该对象交互
- }
- }
- }
CanvasGroup.alpha
实现
一种可放置 Canvas 的元素,可用于修改子 Alpha、Raycasting、Enabled 状态。
画布组可用于修改子元素的状态。
Alpha : 该组UI元素的透明度。注:每个UI最终的透明度是由此值和自身的alpha数值相乘得到。
Interactable : 是否需要交互(勾选的则是可交互),同时作用于该组全部UI元素。
Blcok Raycasts : 是否可以接收图形射线的检测(勾选则接受检测)。注:不适用于Physics.Raycast.。