Detect UI Button Click Event in Update method (169893)

At present Update method of script controls movement of main player. Game HUD panel contains Pause button of game play pause functionality.

When I click on Pause UI Button, player also detects that touch and take its movement regarding that.
So I want to remove this part. So in Update method if I detect this Button click event than I can ignore this irregular movement of player.

How to detect this?

3 Answers

3

Create public method with boolean input variable. Add to your button EventTrigger component. On your pause button assingn this script. If you need release and pressDown assign one with “true” and other with “false”. Or run method ChangePauseState.

Example:

 private bool isGamePaused= false;
    
    private void Update()
    {
             if(isGamePaused)
             {
                  //Do something...
             }
    }
    
    public void ChangeCurrentPauseState()
    {
          isGamePaused = !isGamePaused;
    }
    
    public void ChangePauseState(bool _value)
    {
          isGamePaused = _value;
    }

I updated the question with the classes.

Or add a listener

`
public Button = but = null;

void Awake()
{
  if(but)
    {
         but.OnClick.AddListener(OnButtonClicked);
    }
}

public void OnButtonClicked()
{
 Debug.Log("Button Clicked");
}
`

Basically, you both moving ahead into the wrong direction, I already knew how to detect the click event and detect this event in the update method. At that time, when I was pressing the pause button, a game player also detect this input and behave based on that input. So I want the UI detection system in this way - when I press the pause button, it only remains for that click event - not detected by the game player and change the direction.

Not sure if it’ll work for touch input, but for mouse clicks I use EventSystem.current.IsPointerOverGameObject() to detect when the mouse is over UI element and stop any gameplay actions.

EDIT

using UnityEngine.EventSystems;

...

void Update() {
  if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject()) {
    // player action
  }
}

yes you are in right direction but add full code here so I can mark this as correct :)