- Home /
problem with pause button using time.timescale
i am new and creating a 2D Game i created a pause button that on click activates a pause menu it works. However, when i added this script, the players stop moving, but they can still turn left, right, and when i press shoot button during pause, my player sprite changes to shoot and the bullet appears, he does not move, you can play like this, but it is bizzare I want a script that pauses completely my script and WITHOUT time.TimeScale i tried 10 different ones and none would work.
my script:
using UnityEngine;
using UnityEngine.UI;
public class PauseGame : MonoBehaviour {
void Start() {
GetComponent<Button>().onClick.AddListener(TogglePause);
}
public void TogglePause() {
Time.timeScale = Mathf.Approximately(Time.timeScale, 0.0f) ? 1.0f : 0.0f;
}
}
Simple way to do that, add a single boolean in your pause script, and check that boolean, where you have your player and other script calling to.
Now, simply check, if the pause menu is activated.
e.g. I assume your player and controller scripts have update function ``` void Update() { if (!Pause_$$anonymous$$enu.pause_menu_activated){//Rest of the player code goes here}
} ```
Answer by ShadyProductions · Jan 09, 2020 at 12:43 PM
Setting timescale to 0 only stops physics and update calls that are framerate independent. It does however not stop people from clicking UI buttons or rotating or doing other stuff that does not involve time calculation like instantiating objects etc.
What you can do is have a static variable that verifies if the game is paused:
public static bool IsGamePaused { get { return Time.timeScale == 0; } }
Then for every script you have you will need to check IsGamePaused if so you have to return from the method that does your calculations.
Example:
public void ShootBullet() {
if (IsGamePaused) return;
// other logic
}
Answer by pommerose94 · Jan 09, 2020 at 03:45 PM
I am very new @ShadyProductions I did not completely understood the second script, what is //other logic representing??? and i bind the first script to my PauseGame script, right?
The first part what @ShadyProductions mentioned, is not a script, but rather a static variable which will check if the game is paused or not.
In a very simple terms, you can set the Time.timescale = 0 when player pauses the game, and just add IsGamePaused as a if condition to the rest of your functions which are related to bullets shooting and playermovent etc, Unity will take care the rest of the backend operations.
Seems you should learn some basic C# before you attempt unity.