Hello,
I’m having an issue where my pause menu only activates every other time my gameplay scene is loaded.
When starting the game from either the gameplay scene (build index: 1) or the main menu (build index: 0) the pause menu will function as expected (time freezes, HUD is disabled, pause menu UI enabled, controller line interactors enabled). However if the scene is reloaded (via going back to the main menu and back or upon player death), these attributes won’t trigger until the scene is reloaded once more. This continues to go back and forth forever. I can also trigger the pause menu on and off properly multiple times within the same scene instance while it is working properly.
Getting more specific, in the instances where the pause menu doesn’t work, the Inspector shows the correct game object references. When the menu button on the controller is pressed, the Debug.Log information displays the behavior that is expected, but this is not reflected in the gameplay. Example: Debug.Log("Time Scale: " + Time.timeScale) will display “0” or “1” when it’s supposed to, but the time in-game will not freeze. Also Debug.Log("HUD UI " + hudCanvas.activeSelf) will display “false” when expected, but the Canvas will still be visible in-game. It feels as though every other time the scene is loaded, it obtains references to the wrong instances of the GameObjects (including Time).
Here is the code for the Pause Menu (using Unity 2021.2.11f1):
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.XR.Interaction.Toolkit;
public class PauseMenu : MonoBehaviour
{
[SerializeField] GameObject pauseMenuUI;
[SerializeField] GameObject rightHandController;
[SerializeField] GameObject leftHandController;
[SerializeField] GameObject hudCanvas;
bool gamePaused = false;
public void ToggleMenu() // Triggered from Player script by controller button
{
if (gamePaused)
{
Resume();
}
else
{
Pause();
}
}
void Resume()
{
hudCanvas.SetActive(true);
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
gamePaused = false;
SetControllerProperties(false);
}
void Pause()
{
hudCanvas.SetActive(false);
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
gamePaused = true;
SetControllerProperties(true);
}
void SetControllerProperties(bool isEnabled)
{
rightHandController.GetComponent<LineRenderer>().enabled = isEnabled;
rightHandController.GetComponent<XRInteractorLineVisual>().enabled = isEnabled;
leftHandController.GetComponent<LineRenderer>().enabled = isEnabled;
leftHandController.GetComponent<XRInteractorLineVisual>().enabled = isEnabled;
Debug.Log("HUD UI " + hudCanvas.activeSelf);
Debug.Log("Enabled: " + isEnabled);
Debug.Log("Time Scale: " + Time.timeScale);
}
public bool GetGamePaused()
{
return gamePaused;
}
public void MainMenu() // Triggered by UI Button Press
{
Time.timeScale = 1f;
SceneManager.LoadScene(0);
}
}