Unity3d的UI控制脚本

栏目: 编程语言 · 发布时间: 6年前

内容简介:最近学习了Unity3d游戏界面UI的设计思路,发现自己原来的设计简直就是在瞎搞,特别记录一下,一份代码解决所有按钮与界面切换的逻辑,主要是通过命名按钮与界面名字的耦合以及deleget委托。一言不合,先上代码

最近学习了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));
    }

}

效果图

Unity3d的UI控制脚本

Unity3d的UI控制脚本


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms in Java

Data Structures and Algorithms in Java

Robert Lafore / Sams / 2002-11-06 / USD 64.99

Data Structures and Algorithms in Java, Second Edition is designed to be easy to read and understand although the topic itself is complicated. Algorithms are the procedures that software programs use......一起来看看 《Data Structures and Algorithms in Java》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

URL 编码/解码
URL 编码/解码

URL 编码/解码