unity 一级二级菜单控制脚本,一级菜单按钮为toggle ,控制对应二级菜单父物体显隐,二级菜单父物体下为二级菜单分类父物体,二级菜单分类父物体之下为二级菜单按钮,按钮分toggle和button两类,分别绑定不同方法,关闭二级菜单时对二级菜单按钮做初始化,编写控制脚本并挂载到unity场景,使用MVC框架
时间: 2023-08-07 10:01:59 浏览: 282
以下是使用MVC框架编写的一级二级菜单控制脚本:
Model层:
```
using System.Collections.Generic;
using UnityEngine;
public class MenuModel
{
public Dictionary<string, List<GameObject>> subMenus; //存储二级菜单分类父物体及其下的二级菜单按钮
public MenuModel()
{
subMenus = new Dictionary<string, List<GameObject>>();
}
public void AddSubMenu(string key, GameObject subMenu)
{
if (!subMenus.ContainsKey(key))
{
subMenus.Add(key, new List<GameObject>());
}
subMenus[key].Add(subMenu);
}
}
```
View层:
```
using UnityEngine;
using UnityEngine.UI;
public class MenuView : MonoBehaviour
{
public Toggle menuToggle; //一级菜单按钮
public GameObject subMenuParent; //二级菜单父物体
public void ShowSubMenus(bool isOn)
{
subMenuParent.SetActive(isOn);
}
public void InitSubMenuButtons()
{
foreach (Transform child in subMenuParent.transform)
{
if (child.gameObject.activeSelf)
{
Toggle toggle = child.GetComponent<Toggle>();
if (toggle != null)
{
toggle.isOn = false;
}
else
{
Button button = child.GetComponent<Button>();
if (button != null)
{
button.onClick.RemoveAllListeners();
}
}
}
}
}
}
```
Controller层:
```
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuController : MonoBehaviour
{
public MenuView menuView;
public MenuModel menuModel;
private void Start()
{
InitializeSubMenuButtons();
menuView.menuToggle.onValueChanged.AddListener(ShowSubMenus);
}
private void InitializeSubMenuButtons()
{
foreach (KeyValuePair<string, List<GameObject>> subMenu in menuModel.subMenus)
{
foreach (GameObject subMenuButton in subMenu.Value)
{
if (subMenuButton.activeSelf)
{
Toggle toggle = subMenuButton.GetComponent<Toggle>();
if (toggle != null)
{
toggle.isOn = false;
toggle.onValueChanged.AddListener(delegate { ToggleSubMenu(subMenu.Key, toggle); });
}
else
{
Button button = subMenuButton.GetComponent<Button>();
if (button != null)
{
button.onClick.AddListener(delegate { ClickSubMenuButton(subMenu.Key, button); });
}
}
}
}
}
}
private void ToggleSubMenu(string key, Toggle toggle)
{
List<GameObject> subMenus = menuModel.subMenus[key];
bool isOn = toggle.isOn;
foreach (GameObject subMenu in subMenus)
{
subMenu.SetActive(isOn);
}
if (!isOn)
{
menuView.InitSubMenuButtons();
}
}
private void ClickSubMenuButton(string key, Button button)
{
//TODO: 点击二级菜单按钮后的操作
}
private void ShowSubMenus(bool isOn)
{
menuView.ShowSubMenus(isOn);
if (!isOn)
{
menuView.InitSubMenuButtons();
}
}
}
```
使用方法:
1. 在Unity场景中创建一级菜单按钮和二级菜单父物体;
2. 在二级菜单父物体下创建二级菜单分类父物体,并在分类父物体下创建二级菜单按钮;
3. 给一级菜单按钮绑定Toggle组件,在其中设置Transition为None,并将MenuView中的menuToggle字段绑定到该Toggle组件上;
4. 将MenuView脚本挂载到一级菜单按钮上,并将二级菜单父物体绑定到其中的subMenuParent字段上;
5. 将MenuController脚本挂载到Unity场景中,并将MenuView和MenuModel绑定到其中的menuView和menuModel字段上;
6. 在MenuModel中设置二级菜单分类父物体及其下的二级菜单按钮;
7. 在ClickSubMenuButton方法中编写点击二级菜单按钮后的操作;
8. 运行Unity场景,测试脚本是否正常运行。
阅读全文