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?
I resolved this by iterating over VisualElements 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;
}
You can also use EventSystem.current.IsPointerOverGameObject() after adding an EventSystem to the scene, which was preferable in my use case to the accepted answer.