Unity的UI面板基类

使用这个组件实现淡入淡出

Unity的UI面板基类_第1张图片

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();
        //如果忘记添加脚本
        if (canvasGroup == null)
        {
            canvasGroup = this.gameObject.AddComponent();
        }
    }
    //虚函数,让子类面板可以重写
    protected virtual void Start()
    {
        //调用注册方法
        Init();
    }

    /// 
    /// 注册控件事件方法
    /// 子类必须实现
    /// 
    public abstract void Init();

    /// 
    /// 显示面板
    /// 
    public virtual void ShowMe()
    {
        canvasGroup.alpha = 0;
        isShow = true;
    }
    /// 
    /// 关闭面板
    /// 
    public virtual void HideMe(UnityAction callBack)
    {
        canvasGroup.alpha = 1;
        isShow = false;

        hideCallBack = callBack;
    }
    // Update is called once per frame
    void Update()
    {
        //淡入
        //显示 并且 透明度不为1
        if (isShow && canvasGroup.alpha!=1)
        {
            //透明度从0加到1
            canvasGroup.alpha += alphaSpeed * Time.deltaTime;
            if (canvasGroup.alpha>=1)
            {
                canvasGroup.alpha = 1;
            }
        }
        //淡出
        //不显示 并且 透明度不为0
        else if (!isShow && canvasGroup.alpha!=0)
        {
            //透明度从1减到0
            canvasGroup.alpha -= alphaSpeed * Time.deltaTime;
            if (canvasGroup.alpha <=0)
            {
                canvasGroup.alpha = 0;
                //淡出后 执行逻辑
                hideCallBack?.Invoke();
            }
        }
    }
}

你可能感兴趣的:(ui)