Runtime
using SoyWar.UIToolkit;
using SoyWar.UIToolkit.Extensions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;
public class CustomElementComponent : UIToolkitComponent<CustomElement>
{
[SerializeField] private UnityEvent<string> _onCustomEvent = new();
public UnityEvent<string> OnCustomEvent => _onCustomEvent;
// Call when a new element is added based on the selector (pseudo-classes are not taken into account)
protected override void Set(CustomElement element)
{
base.Set(element);
// Example: Use KeyUpEvent to create a custom Event
element.RegisterCallback<KeyUpEvent>(OnChange);
}
// Call when a new element is removed based on the selector (pseudo-classes are not taken into account)
protected override void Unset(CustomElement element)
{
base.Unset(element);
element.UnregisterCallback<KeyUpEvent>(OnChange);
}
private void OnChange(KeyUpEvent evt)
{
// Example: Call the event only if the element is active (pseudo-classes are taken into account) inside the component and if the text length is even
CustomElement customElement = (CustomElement)evt.currentTarget;
if (this.IsElementActive(customElement) && customElement.text.Length % 2 == 0)
{
_onCustomEvent.Invoke(customElement.text);
}
}
}
Editor
using UnityEditor;
using SoyWar.UIToolkit.Editor.Component;
[CustomEditor(typeof(CustomElementComponent))]
public class CustomElementComponentEditor : UIToolkitComponentEditor
{
protected override void OnEnable()
{
base.OnEnable();
SerializedProperty onCustomEvent = serializedObject.FindProperty("_onCustomEvent");
// Adds the Unity Event to the list of available events
AddEvent("Custom Event Name", onCustomEvent);
}
}