Prevent pointer clicks through elements

I am making a drawing application using UI toolkit, but when I have an element “popup” over an the draw area, both the popup and the draw area get pointer clicks.

I am using a callback for the drawarea, and tried both “Trickledown” and “NoTrickledown”, but nothing blocks the clicks.

ex callback for draw area:

drawareaVisualElement.RegisterCallback<PointerDownEvent>(OnPointerDown, TrickleDown.NoTrickleDown);

The popup element panels don’t really have a callback (only the controls do - radiobuttons, etc.), so not sure how I would handle “trickledown” for the whole panel.

Have you tried calling StopPropagation on the event inside of OnPointerDown?

Hey, thanks for the quick reply :slight_smile:

So looking online I would use it as “evt.StopPropagation();”. But when I put it under “OnPointerDown” or even “OnPointerEnter” of the draw area, clicks on my popup panel still “draw” under it.

Would I need to add the StopPropagation() on my popup panel somehow instead?

Edit: So I created an OnPointerDown callback for my popup panel, and in there I added the StopPropogation(). This seems to work now. But does that mean I have to create a callback for every single popup I create in my UI to stop the propogation? Or is there a universal way of defaulting to StopPropogation?

Yes you will need to do it for every popup element.

You may want to create a specific VisualElement type that does this

class BlockerElement : VisualElement {
 #if UNITY_2023_2_OR_NEWER
     protected override void HandleEventBubbleUp(EventBase evt) => OnHandleEvent(evt);
 #else
     protected override void ExecuteDefaultAction(EventBase evt) => OnHandleEvent(evt);
 #endif
 
     void OnHandleEvent(EventBase evt)
     {
         if (evt is AttachToPanelEvent)
              RegisterCallback<PointerDownEvent>(StopPointerPropagation, TrickleDown.TrickleDown);
         else if (evt is DetachFromPanelEvent)
              UnregisterCallback<PointerDownEvent>(StopPointerPropagation, TrickleDown.TrickleDown);
     }
     void StopPointerPropagation(PointerDownEvent evt) => evt.StopPropagation();
 }

This page has good information on how events propagate

Depending how the hierarchy’s built you may need to keep the “drawing” logic during the BubbleUp phase so the popups/overlays have a chance to stop event propagation before the canvas has a chance to handle the event itself

That’s awesome! :slight_smile: Thank you so much for answering my question. Need more people like you on the Unity team.

1 Like

I can’t take full credit for that one, another team member gave me the answer :smile:

1 Like