游戏UI管理

作者:追风剑情 发布于:2022-10-26 15:11 分类:Unity3d

一、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() { }
}


标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号