Search code examples
c#unity-game-engineunity-ui

How to use buttons without intercepting the game controls?


I have a mobile game where the only thing you have to do is to tap to jump,now i added a pause menu and when i click it the player still jumps,after i click on resume button the player also jumps and makes the game annoying

How to fix?

Code:

 public void Pause()
{    
  Time.timeScale = 0;
  panel.SetActive(true);
         
    
}
public void Resume()
{
    Time.timeScale = 1;
    panel.SetActive(false);
    
}

And for jump if u ask(it's called in void update):

 void Jump()
{
    if (Input.GetMouseButtonDown(0)) 
    {
         rb.AddForce(Arrow.transform.right * -ImpulseForce * Time.fixedDeltaTime, ForceMode2D.Impulse);
    }
}

Solution

  • Depending on your setup, one easy way is to check if the current event is over an UI GameObject before adding the force to your rigidbody, using EventSystem.current.IsPointerOverGameObject():

    void Jump()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
             rb.AddForce(Arrow.transform.right * -ImpulseForce * Time.fixedDeltaTime, ForceMode2D.Impulse);
        }
    }
    
    

    Alternatives would be to use raycasts to check where a click went (UI or not) or implement one of the IPointerClickHandler / IPointerDownHandler interfaces.