1. 程式人生 > >Unity3d的UI控制指令碼

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));
    }

}

效果圖