Learn how to create a functional 2D pause menu in Unity with this step-by-step tutorial! We'll guide you through setting up a pause menu with Resume, Restart, and Home buttons, and show you how to integrate a dedicated Pause button into your UI. Follow along as we walk you through creating UI elements, scripting their functionality, and testing the pause menu to ensure it works seamlessly in your game. Perfect for beginners and those looking to enhance their Unity 2D game with a smooth pause feature.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
3 Unity Projects Only $70 - ON SALE!!!!
1. Water Sort 9000 Levels
2. Ball Sort Sort 9000 Levels
3. Sling Shot 250 Levels
Contact: unitycoderz2022@gmail.com
=========================================================
Script:
PauseMenu.cs
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PauseMenu : MonoBehaviour
{
public GameObject pauseMenuPanel;
public Button resumeButton;
public Button restartButton;
public Button homeButton;
public Button pauseButton;
private bool isPaused = false;
void Start()
{
// Initialize the pause menu as inactive
pauseMenuPanel.SetActive(false);
// Add button listeners
resumeButton.onClick.AddListener(ResumeGame);
restartButton.onClick.AddListener(RestartGame);
homeButton.onClick.AddListener(GoHome);
pauseButton.onClick.AddListener(PauseGame); // Add listener for Pause Button
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (isPaused)
{
ResumeGame();
}
else
{
PauseGame();
}
}
}
void PauseGame()
{
pauseMenuPanel.SetActive(true);
Time.timeScale = 0f; // Freeze game time
isPaused = true;
}
void ResumeGame()
{
pauseMenuPanel.SetActive(false);
Time.timeScale = 1f; // Resume game time
isPaused = false;
}
void RestartGame()
{
Time.timeScale = 1f; // Ensure time is resumed before restarting
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
void GoHome()
{
Time.timeScale = 1f; // Ensure time is resumed before loading another scene
SceneManager.LoadScene("MainMenu"); // Replace "MainMenu with the name of your home scene
}
}