Unity功能——设置提示面板的显示与掩藏

这里以提示面板的显示与掩藏举例,鼠标靠近物体时提示面板显示,离开物体时提示面板掩藏;

1、添加CanvasGroup组件

对要控制的UI身上添加CanvasGroup这个UGUI组件,后续通过该组件设置对象的显示掩藏;

2、代码设置CanvasGroup里的Alpha值

0为面板掩藏,1为面板显示,使用差值顺滑渐变显示掩藏面板;

using UnityEngine;
using UnityEngine.UI;

public class InfoTips : MonoBehaviour
{
    private float targetAlpha=0;
    private float smoothing = 1f;
    private CanvasGroup canvasGroup;
    private void Start()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        smoothing = 5f;
    }
    private void Update()
    {
        if (canvasGroup.alpha != targetAlpha)
        {
            canvasGroup.alpha = Mathf.Lerp(canvasGroup.alpha, targetAlpha, smoothing * Time.deltaTime);
            if (Mathf.Abs(canvasGroup.alpha - targetAlpha) < 0.01f)
            {
                canvasGroup.alpha = targetAlpha;
            }
        }
    }
    public void ShowTips()
    {
        targetAlpha = 1;
    }
    public void HideTips()
    {
        targetAlpha = 0;
    }
}

3、调用面板显示掩藏函数

这里使用IPointerEnterHandler,IPointerExitHandler接口监听事件,在其实现方法里调用面板显示与掩藏的函数;修改了Alpha值,上面的Tips脚本的Update()里进行自动更新面板的显示与掩藏;

using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// 物品槽
/// </summary>
public class Slot : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler
{
    public InfoTips tips
    
    public void OnPointerEnter(PointerEventData eventData)
    {
        tips.ShowTips();
    }
    public void OnPointerExit(PointerEventData eventData)
    {
        tips.HideTips();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值