使用这个组件实现淡入淡出
public abstract class BasePanel : MonoBehaviour
{//控制面板透明度 用于淡入淡出private CanvasGroup canvasGroup;//淡入淡出速度private float alphaSpeed = 10;//隐藏还是显示public bool isShow = false;//隐藏完毕后做的事private UnityAction hideCallBack = null;protected virtual void Awake(){//获取面板挂载的组件canvasGroup = GetComponent<CanvasGroup>();//如果忘记添加脚本if (canvasGroup == null){canvasGroup = this.gameObject.AddComponent<CanvasGroup>();}}//虚函数,让子类面板可以重写protected virtual void Start(){//调用注册方法Init();}/// <summary>/// 注册控件事件方法/// 子类必须实现/// </summary>public abstract void Init();/// <summary>/// 显示面板/// </summary>public virtual void ShowMe(){canvasGroup.alpha = 0;isShow = true;}/// <summary>/// 关闭面板/// </summary>public virtual void HideMe(UnityAction callBack){canvasGroup.alpha = 1;isShow = false;hideCallBack = callBack;}// Update is called once per framevoid Update(){//淡入//显示 并且 透明度不为1if (isShow && canvasGroup.alpha!=1){//透明度从0加到1canvasGroup.alpha += alphaSpeed * Time.deltaTime;if (canvasGroup.alpha>=1){canvasGroup.alpha = 1;}}//淡出//不显示 并且 透明度不为0else if (!isShow && canvasGroup.alpha!=0){//透明度从1减到0canvasGroup.alpha -= alphaSpeed * Time.deltaTime;if (canvasGroup.alpha <=0){canvasGroup.alpha = 0;//淡出后 执行逻辑hideCallBack?.Invoke();}}}
}