UI Toolkit ComponentUI Toolkit Component
UI Toolkit ComponentUI Toolkit Component
  • Docs
  • API
  • Changelog
  • Unity Asset Store
  • Bug report
  • Getting Started
  • Essentials
    • How To Import a Demo
    • How To Add a Style Sheet
    • How To Add an Event
    • List of Pseudo Classes
    • List of Events
  • Advanced
    • How To Get a VisualElement
    • How To Find a VisualElement
    • How To Check a VisualElement
    • How To Create a custom Pseudo Class
    • How To Create a custom UI Toolkit Component
    • How To Add a custom UI Toolkit GameObject
Generated by DocFX
(with DiscordFX + SingulinkFX)

Search Results for

    How To Add a custom UI Toolkit Component

    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);
        }
    }