BITKit/Packages/Runtime~/Unity/Scripts/UX/SubMenu/SubMenu.cs

73 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.Events;
namespace BITKit
{
public struct NewSubMenu
{
public string name;
public Vector2 position;
public IEnumerable<SubAction> actions;
}
public struct SubAction
{
public string name;
public UnityAction action;
}
public class SubMenu : BITBehavior
{
[Header(Constant.Header.Components)]
public UIDocument document;
Label label;
VisualElement context;
VisualElement root;
void Start()
{
Data.AddListener<IEnumerable<SubAction>>(OnAction);
Data.AddListener<NewSubMenu>(OnContextMenu);
root = document.rootVisualElement;
label = root.Q<Label>("Label");
context = root.Q("Context");
SetActive(false);
root.RegisterCallback<PointerLeaveEvent>(x =>
{
SetActive(false);
});
}
void OnContextMenu(NewSubMenu contextMenu)
{
label.text = contextMenu.name;
OnAction(contextMenu.actions);
root.style.left = contextMenu.position.x - 4f;
root.style.top = contextMenu.position.y - 4f;
}
void OnAction(IEnumerable<SubAction> actions)
{
SetActive(true);
actions.ForEach(x =>
{
var button = new Button();
button.text = x.name;
button.clicked += () =>
{
x.action.Invoke();
SetActive(false);
};
context.Add(button);
});
}
public override void SetActive(bool active)
{
if (active)
{
}
else
{
context.Clear();
}
document.rootVisualElement.SetActive(active);
}
}
}