- Home /
I want OnClick to fire the same frame that the button is clicked
I made a pause button that then pauses the game by setting Time.timescale = 0. I use the editors On Click {} event. The code looks like this:
public class PauseAndPlay : MonoBehaviour { public GameObject pauseButton; public GameObject playButton;
public void Pause()
{
SaveAndLoad.saveAndLoad.Pause();
pauseButton.SetActive(false);
playButton.SetActive(true);
}
public void Play()
{
pauseButton.SetActive(true);
playButton.SetActive(false);
SaveAndLoad.saveAndLoad.Unpause();
}
}
The problem then comes when my player continues to move for a bit even though the game has been paused with Time.timescale. I move my player like so:
//If mousepress is detected if (Input.GetMouseButton(0)) {
//set the place as a vector
targetPos = cam.ScreenToWorldPoint(Input.mousePosition);
targetPos.z = 0;
//Get screen height and width
screenBounds = cam.ScreenToWorldPoint(new Vector3 (Screen.width, Screen.height, 0));
//Clamp the target position so that player can't leave camera view
targetPos.y = Mathf.Clamp(targetPos.y, (screenBounds.z - renderSizeY), (screenBounds.y-renderSizeY));
targetPos.x = Mathf.Clamp(targetPos.x, (screenBounds.z - renderSizeX), (screenBounds.x - renderSizeX -2/*-2 because of next line where + Vector3.right * 2 */));
//move to the place, but a bit forward so the finger doesn't obscure the sprite. ActualSpeed() is an int * Time.deltaTime
transform.position = Vector3.MoveTowards(transform.position,targetPos + Vector3.right * 2, ActualSpeed());
}
This happens in the Update loop. So I suspect, after a few tests, that the OnClick event doesn't happen until you stop clicking, essentially GetMouseButtonUp(0) sort of thing. With the way movement is implemented in my game I would need to pause it on the GetMouseButtonDown(0) instead. Anyone know how this can be achieved?
Answer by Dragonalias · Apr 19, 2018 at 09:26 PM
Found the answer myself. In case someone else needs it: Use OnPointerDown
Just do it the same way as in the link, even making it public. OnPointerDown will fire when the object is clicked.