- Home /
How to use EventSystems handlers with UI Toolkit documents
In a legacy project I have a script that I use to dispatch events from various handlers, it looks more or less like this:
public class InputEventBehaviour : MonoBehaviour,
IPointerClickHandler,
IDragHandler
{
void OnPointerClick(PointerEventData pointerEventData)
=> OnPointerClickCallback?.Invoke(pointerEventData);
void OnDrag(PointerEventData pointerEventData)
=> OnDragCallback?.Invoke(pointerEventData);
public static event Action<PointerEventData> OnPointerClickCallback = null;
public static event Action<PointerEventData> OnDragCallback = null;
}
In order to work properly, this script is attached to a GameObject
below the main canvas as such:
My issue is that the canvas is blocking the UIDocument
, making it non interactable.
For that reason I am now trying to find a way to use my script without the legacy canvas, but I have found very little information from the documentation about this case.
Unfortunately, attaching my script to the UIDocument
does not work, the callbacks are not triggered.
Is it even possible to still implement EventSystem
handlers with UIToolkit
? What should I change in order to make my script work again?
Answer by andrew-lukasik · Jan 31 at 05:27 PM
using UnityEngine;
using UnityEngine.UIElements;
public class AnEventfulComponent : MonoBehaviour
{
[SerializeField] UIDocument _uiDocument = null;
public static event System.Action<PointerDownEvent> OnPointerDown
= (e)=> Debug.Log($"pointer down @ {(Vector2)e.position}");
public static event System.Action<PointerUpEvent> OnPointerUp
= (e)=> Debug.Log($"pointer up @ {(Vector2)e.position}");
public static event System.Action<PointerMoveEvent> OnPointerDrag
= (e)=> Debug.Log($"pointer move @ {(Vector2)e.position}");
void OnEnable ()
{
var root = _uiDocument.rootVisualElement;
root.RegisterCallback<PointerDownEvent>( (e) => OnPointerDown(e) );
root.RegisterCallback<PointerUpEvent>( (e) => OnPointerUp(e) );
root.RegisterCallback<PointerMoveEvent>(
(e) => { if( e.pressedButtons!=0 ) OnPointerDrag(e);}
);// e.pressedButtons is a bitmask
}
}
Your answer
Follow this Question
Related Questions
Event System value of mouse position is wrong. 0 Answers
How to ignore some events occurrence 2 Answers
UI Toolkit, Gray out a button using a second button 1 Answer
Unity 2021.2 UI Toolkit Version 0 Answers
UI Event System Question 0 Answers