鸟语天空
游戏UI管理
post by:追风剑情 2022-10-26 15:11

一、UI栈

用栈来管理UI,方便回退。类似Android的Activity。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// UI栈
/// </summary>
public sealed class UIStack
{
    private static Stack<UIMonoBehaviour> stack = new Stack<UIMonoBehaviour>();

    static UIStack()
    {
        SceneManager.sceneUnloaded += OnSceneUnloaded;
    }

    private static void OnSceneUnloaded(Scene scene)
    {
        Debug.Log("UIStack Clear");
        Clear();
    }

    public static void Push(UIMonoBehaviour ui)
    {
        stack.Push(ui);
    }

    public static UIMonoBehaviour Pop()
    {
        if (stack.Count == 0)
            return null;
        var ui = stack.Pop();
        return ui;
    }

    public static void Clear()
    {
        stack.Clear();
    }
}


using UnityEngine;
/// <summary>
/// UI基类
/// </summary>
public class UIMonoBehaviour : GameEventBehaviour
{
    //UI根节点
    [SerializeField]
    private GameObject root;

    // UI是否激活
    public bool IsActive()
    {
        if (!isActiveAndEnabled)
            return false;

        if (root == null)
            return gameObject.activeInHierarchy;
        return root.activeInHierarchy;
    }

    // 设置UI激活状态
    public void SetActive(bool value)
    {
        if (root == null)
            gameObject.SetActive(value);
        else
            root.SetActive(value);
    }

    // 切换激活状态
    public void SwitchActive()
    {
        if (IsActive())
            Hide();
        else
            Show();
    }

    // 显示UI
    public void Show()
    {
        SetActive(true);
        OnShow();
    }

    // 回退显示
    private void BackShow()
    {
        SetActive(true);
        OnBackShow();
    }

    // 隐藏UI
    public void Hide()
    {
        SetActive(false);
        OnHide();
    }

    // 隐藏当前UI并入栈
    public void HidePush()
    {
        Hide();
        UIStack.Push(this);
    }

    // 隐藏当前UI并返回上级UI
    public void HideBack()
    {
        Hide();
        var ui = UIStack.Pop();
        if (ui != null)
            ui.BackShow();
    }

    // 判断UI是否已销毁
    public bool IsDestroyed()
    {
        return this == null;
    }

    // 显示回调
    protected virtual void OnShow() { }
    // 回退显示回调
    protected virtual void OnBackShow() { }
    // 隐藏回调
    protected virtual void OnHide() { }
}


评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容