- Home /
[5.4.1f1] After clicking on a Button, pressing Space fires the Button.onClick event
Like the title says.
I have a pause Button that pauses/unpauses the game. Pressing the Spacebar has the same effect.
It works fine with the button. The Spacebar works too, until I press the Button once. From that point on, everytime I press the Spacebar the Button fires its onClick event.
This is how I listen to the Button: _PauseButton.onClick.AddListener(gameManager.OnPauseButtonClick);
Here is the relevant code handling the Input: void Update () { HandleInput ();
if (!_Paused) {
_DayTimer += Time.deltaTime;
if (_DayTimer >= DAYLENGTH) {
_DayTimer -= DAYLENGTH;
_Days++;
_DateView.SetDate (_Days);
}
}
}
public void OnPauseButtonClick ()
{
HandlePausing ();
}
private void HandleInput ()
{
if (!_SpaceKeyDown && Input.GetKeyDown (KeyCode.Space)) {
_SpaceKeyDown = true;
} else if (_SpaceKeyDown && !Input.GetKeyDown (KeyCode.Space)) {
_SpaceKeyDown = false;
HandlePausing ();
}
}
private void HandlePausing ()
{
Debug.Log ("GameManager:HandlePausing:called! Pause=" + _Paused);
if (!_Paused) {
_Paused = true;
_DateView.SetPause (true);
} else {
_Paused = false;
_DateView.SetPause (false);
}
}
Answer by saschandroid · Oct 11, 2016 at 01:13 PM
I guess that your button is still selected and because of this 'fired' if you press the space bar. If that is the problem you could try to 'deselect' the button after it is clicked by:
using UnityEngine.EventSystems;
public void OnPauseButtonClick ()
{
HandlePausing ();
// Deselect everything ... probably you have to move this to another place.
EventSystem.current.SetSelectedGameObject(null);
}
Answer by saschandroid · Oct 11, 2016 at 05:22 PM
There is another solution for this: In the inspector go to the Button script component and set Navigation to None. This should deselect the button after a click automatically.
I believe this to be a sure answer alongside the currently accepted answer as this offers an approach to undertake a resolution via the Unity Editor and in the Button component inspector which offers non-technical users an approach to resolving this issue without additional code complexity.
Your answer
Follow this Question
Related Questions
How to create a turn based battle system? 3 Answers
[C#] Unity asks for a } for a reason I don't know ( '}' expected ) 1 Answer
how to track UI buttons on Image targets 0 Answers
C# UI list item drag onto 2d sprite in world space? 1 Answer
Gamepad menu navigation with uGUI not working as expected. 1 Answer