Unity3d的UI控制脚本

最近学习了Unity3d游戏界面UI的设计思路,发现自己原来的设计简直就是在瞎搞,特别记录一下,

一份代码解决所有按钮与界面切换的逻辑,主要是通过命名按钮与界面名字的耦合以及deleget委托。

先上代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIController : MonoBehaviour {

    Dictionary<string, GameObject> panels = new Dictionary<string, GameObject>();
    Stack<GameObject> history = new Stack<GameObject>();
    GameObject[] btns;
    public GameObject StartPanel;
    GameObject currentPanel;

    private void Start()
    {
        GameObject[] myPanels = GameObject.FindGameObjectsWithTag("UIPanel");
        btns = GameObject.FindGameObjectsWithTag("UIBtn");
        foreach(GameObject g in myPanels)
        {
            Debug.Log(g.name.Substring(2));
            panels.Add(g.name.Substring(2),g);
            currentPanel = StartPanel;
            if(g != StartPanel)
            {
                g.SetActive(false);
            }
        }

        foreach(GameObject b in btns)
        {
            b.GetComponent<Button>().onClick.AddListener(delegate () {
                OnButtonClickEvent(b);
            });
        }


    }
	
    public void ShowPanel(string panelName)
    {
        GameObject newPanel = null;
        if (panelName != "Back")
        {
            if (panels.ContainsKey(panelName))
            {
                history.Push(currentPanel);
                newPanel = panels[panelName];
            }

        }else if (history.Count > 0) {
            newPanel = history.Pop();
        }

        if(newPanel != null && currentPanel != null)
        {
            currentPanel.SetActive(false);
            currentPanel = newPanel;
            currentPanel.SetActive(true);
        }
    }

    public void OnButtonClickEvent(GameObject g)
    {
        ShowPanel(g.name.Substring(2));
    }

}

效果图

扫描二维码关注公众号,回复: 2681829 查看本文章


 

猜你喜欢

转载自blog.csdn.net/qq_39668086/article/details/81414948
今日推荐