Search code examples
c#unity-game-engine2d

play if the player click in a blank space unity 2d


I'm making a 2d game for mobile and created a pause button on the canvas. the problem is that when i click the pause button the player shoots. I wish there was a way to block the shot when the touch is on an element of the UI. is there any simple way to do this?

this is the code I wrote to detect clicks:

if(Input.touchCount > 0)
        {
            touch_ = Input.GetTouch(0);
            
            if(touch_.phase == TouchPhase.Began)
            {
                touching = true;
                touch_began_fun();
            }
            if(tocando)
            {
                toching_fun();
            }
            if(touch_.phase == TouchPhase.Ended)
            {
                touching = false;
                touch_ended_fun();
            }
        }

Solution

  • Check the current selected game object of the EventSystem is null. If it is not null, the touch is on a UI element.

    if(Input.touchCount > 0)
    {
        touch_ = Input.GetTouch(0);
    
        if(touch_.phase == TouchPhase.Began && EventSystem.current.currentSelectedGameObject == null)
        {
            touching = true;
            touch_began_fun();
        }
        if(tocando)
        {
            toching_fun();
        }
        if(touch_.phase == TouchPhase.Ended)
        {
            touching = false;
            touch_ended_fun();
        }
    }