这里以提示面板的显示与掩藏举例,鼠标靠近物体时提示面板显示,离开物体时提示面板掩藏;
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();
}
}