- Home /
UI Toolkit - prevent click through visual element
Hello!
I've setup UI Toolkit button as a part of my in game interface and made it intractable. My game has ground that consists of 2D gameobjects (tiles). Player can press on these tiles to perform different actions. But whenever I press on button, both button event and tile event are triggered. I want to trigger button actions only, when I press on the button.
I've tried to switch from Unity UI to new Input System, but this doesn't give any results, the problem still exists.
Does anybody know how to prevent event execution of gameobject action when UI toolkit button is clicked?
Answer by andrew-lukasik · Jan 15 at 01:34 AM
I resolved this by iterating over VisualElement
s under the cursor then testing background colors of every element intersecting this coordinate and interpreting alpha!=0
as blocked click. Simple, works.
MyUIController.cs:
[SerializeField] UIDocument _uiDocument = null;
bool IsPointerOverUI ( Vector2 screenPos )
{
Vector2 pointerUiPos = new Vector2{ x = screenPos.x , y = Screen.height - screenPos.y };
List<VisualElement> picked = new List<VisualElement>();
_uiDocument.rootVisualElement.panel.PickAll( pointerUiPos , picked );
foreach( var ve in picked )
if( ve!=null )
{
Color32 bcol = ve.resolvedStyle.backgroundColor;
if( bcol.a!=0 && ve.enabledInHierarchy )
return true;
}
return false;
}
MyTileComponent.cs:
void OnMouseDown ()
{
Vector2 pointerScreenPos = Pointer.current.position.ReadValue();
if( !myUIController.IsPointerOverUI(pointerScreenPos) )
OnTileClicked();
}
Very smart solution, thank you! Spent a couple of days brainstor$$anonymous$$g this issue, but that approach didn't cross my $$anonymous$$d :)
I'm using the old input system and this does not seem to work in editor if the game aspect ratio is on "Free Aspect". I'm using Input.mousePosition.
I found a more reliable solution:
public Vector2 MousePosition
{
get
{
var mousePos = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
return RuntimePanelUtils.ScreenToPanel(_root.panel, mousePos);
}
}