unity 一级二级菜单控制脚本,一级菜单点击控制对应二级菜单父物体显隐,二级菜单对应单独方法,使用MVC框架
时间: 2023-08-07 18:01:59 浏览: 82
以下是一个简单的Unity菜单控制脚本,使用MVC框架,实现了一级菜单点击控制对应二级菜单父物体显隐,以及二级菜单对应的单独方法。
首先,我们需要创建一个菜单项的Model,里面包含菜单项的名称和对应的二级菜单的Prefab:
```
public class MenuItemModel
{
public string Name;
public GameObject SubMenuPrefab;
public MenuItemModel(string name, GameObject subMenuPrefab)
{
Name = name;
SubMenuPrefab = subMenuPrefab;
}
}
```
接下来,我们创建一个菜单项的View,用于显示菜单项的名称,并且在点击时通知Controller:
```
public class MenuItemView : MonoBehaviour, IPointerClickHandler
{
public Text NameText;
private MenuItemModel _model;
private MenuController _controller;
public void Init(MenuItemModel model, MenuController controller)
{
_model = model;
_controller = controller;
NameText.text = _model.Name;
}
public void OnPointerClick(PointerEventData eventData)
{
_controller.OnMenuItemClicked(_model);
}
}
```
然后,我们创建一个菜单控制器Controller,用于处理菜单项的点击事件,控制对应二级菜单的显隐,并调用对应的二级菜单方法:
```
public class MenuController : MonoBehaviour
{
public Transform SubMenuParent;
public List<MenuItemModel> MenuItems;
private Dictionary<string, GameObject> _subMenus = new Dictionary<string, GameObject>();
private void Start()
{
foreach (var menuItem in MenuItems)
{
var menuItemGo = new GameObject(menuItem.Name);
menuItemGo.transform.SetParent(transform);
var menuItemView = menuItemGo.AddComponent<MenuItemView>();
menuItemView.Init(menuItem, this);
}
}
public void OnMenuItemClicked(MenuItemModel model)
{
if (!_subMenus.ContainsKey(model.Name))
{
var subMenu = Instantiate(model.SubMenuPrefab, SubMenuParent);
_subMenus.Add(model.Name, subMenu);
}
var subMenuGo = _subMenus[model.Name];
if (subMenuGo.activeSelf)
{
subMenuGo.SetActive(false);
}
else
{
subMenuGo.SetActive(true);
subMenuGo.GetComponent<SubMenuController>().OpenSubMenu();
}
}
}
```
最后,我们创建一个二级菜单的Controller,用于处理二级菜单的方法:
```
public class SubMenuController : MonoBehaviour
{
public void OpenSubMenu()
{
Debug.Log("SubMenu opened!");
}
}
```
这样,我们就完成了一个简单的Unity菜单控制脚本,使用MVC框架,实现了一级菜单点击控制对应二级菜单父物体显隐,以及二级菜单对应的单独方法。
阅读全文