Skip to content

Instantly share code, notes, and snippets.

@Kurante2801
Created December 25, 2022 16:28
Show Gist options
  • Save Kurante2801/74c92a5b1e6d8dd943833d5e362cc874 to your computer and use it in GitHub Desktop.
Save Kurante2801/74c92a5b1e6d8dd943833d5e362cc874 to your computer and use it in GitHub Desktop.
Tab Menu for Unity UI Builder
using UnityEngine.UIElements;
public class TabMenu : VisualElement
{
public new class UxmlFactory : UxmlFactory<TabMenu, UxmlTraits> { }
public new class UxmlTraits : VisualElement.UxmlTraits
{
UxmlBoolAttributeDescription m_canToggle = new() { name = "can-toggle", defaultValue = false };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
ve.RegisterCallback<AttachToPanelEvent>(OnAttach);
var menu = ve as TabMenu;
menu.canToggle = m_canToggle.GetValueFromBag(bag, cc);
}
private void OnAttach(AttachToPanelEvent e)
{
var menu = e.currentTarget as TabMenu;
menu.GetTabs()?.ForEach(tab => tab.RegisterCallback<ClickEvent, TabMenu>(OnClick, menu));
}
private void OnClick(ClickEvent e, TabMenu menu)
{
var tab = e.currentTarget as Button;
bool active = tab.ClassListContains("tabSelected");
menu.GetTabs()?.ForEach(button => button.RemoveFromClassList("tabSelected"));
menu.GetContents()?.ForEach(ve => ve.RemoveFromClassList("contentSelected"));
if (menu.canToggle && active) return;
tab.AddToClassList("tabSelected");
// Searches for a content with the same name as the tab inside the content child
menu.Q("content")?.Q<VisualElement>(tab.name.Replace("Tab", "Content"))?.AddToClassList("contentSelected");
}
}
public UQueryBuilder<Button>? GetTabs() => this.Q("tabs")?.Query<Button>(className: "tab");
public UQueryBuilder<VisualElement>? GetContents() => this.Q("content")?.Query<VisualElement>(className: "content");
public bool canToggle { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment