Hey Guys! I have recently switched from JS to C# which I just found out required me to go from Update() to IEnumerator when making my Pause Menu script.. So, can someone help me correct my current broken script, so that the game sets Menu active, while freezing the game on first press of the escape key, while doing the opposite on the second push? Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Pause : MonoBehaviour { public GameObject Menu; bool Freeze = false; void Start () { } private IEnumerator Pausemenu() { while (Input.GetKey(KeyCode.Escape) && Freeze == false) { Menu.SetActive(true); Time.timeScale = 0.0f; yield return new WaitForSeconds(1); Freeze = true; } while (Input.GetKey(KeyCode.Escape) && Freeze == true) { Menu.SetActive(false); Time.timeScale = 1; yield return new WaitForSeconds(1); Freeze = false; } } }
You don't need IEnumerator. Try this by danivdwerf https://answers.unity.com/questions/1230216/a-proper-way-to-pause-a-game.html : Code (CSharp): void Update(){ if(Input.GetKeyDown(KeyCode.Escape)){ if(Menu.activeInHierarchy){ Time.timeScale = 0; Menu.SetActive(false); } else { Time.timeScale = 1; Menu.SetActive(true); } } }
Alright, so I tried this but when "escape" is pressed the menu wil open and close a million times / second. So I have tried using a coroutine, but since Update is not called during Time.timeScale = 0, I can't close the menu again, any help to get? My new code Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pause2 : MonoBehaviour { public GameObject Menu; bool Freeze = false; void Start() { } void Update() { if (Input.GetKey(KeyCode.Escape) && Time.timeScale == 1) { StartCoroutine(Paused()); } if (Input.GetKey(KeyCode.Escape) && Time.timeScale == 0) { StartCoroutine(unPaused()); } } private IEnumerator Paused() { Time.timeScale = 0; Menu.SetActive(true); yield return new WaitForSeconds(1.0f); } private IEnumerator unPaused() { yield return new WaitForSeconds(0.5f); Time.timeScale = 1; Menu.SetActive(false); } }
Sorry for late reply! Try using Input.GeyKeyDown() instead of Input.GetKey() because Input.GetKey() returns true when you hold it. Input.GetKeyDown() returns true once. Try doing that without using IEnumerator. Code (CSharp): void Update() { if (Input.GetKeyDown(KeyCode.Escape) && Time.timeScale == 1) { Time.timeScale = 0; Menu.SetActive(true); } if (Input.GetKeyDown(KeyCode.Escape) && Time.timeScale == 0) { Time.timeScale = 1; Menu.SetActive(false); } }
Ahh yes of course! I will try it out later, but it makes perfect sense. Thanks a lot for helping a blind man!