How to make sure no button is clicked?

if ((Input.GetKey(KeyCode.Space)) || Input.GetMouseButton(0) && EventSystem.current.currentSelectedGameObject != Button)

My player can press anywhere on the screen to move, but the problem is that there are also buttons and when the player touches/clicks those, the if statement shouldn’t fire. So how do I detect if any ui element/button is being currently clicked/hit by touch?

You can use these methods to check whether the player is touching the buttons or not.

private void Update()
{
    if (IsPointerOverUi(EventSystem.current)) Debug.Log("Mouse is over UI");
    if (IsPointerOverUiElement<Button>  (EventSystem.current)) Debug.Log("Mouse is over Button");
    if (IsPointerOverUiElement<Image>   (EventSystem.current)) Debug.Log("Mouse is over Image");
    if (IsPointerOverUiElement<Dropdown>(EventSystem.current)) Debug.Log("Mouse is over Dropdown");
}

/// <summary>
/// Returns true if the user touches any ui element
/// </summary>
private static bool IsPointerOverUi(EventSystem eventSystem)
{
    return eventSystem.IsPointerOverGameObject() || eventSystem.currentSelectedGameObject != null;
}

/// <summary>
/// Returns true if the user touches a specific ui element
/// </summary>
private static bool IsPointerOverUiElement<TElement>(EventSystem eventSystem)
{
    if (eventSystem.currentSelectedGameObject == null) return false;
    return eventSystem.currentSelectedGameObject.GetComponent<TElement>() != null;
}

Thank you, that works. :slight_smile: