Menu
CoddyTech

Play Again

Lesson 12 of 14 in Coddy's Unity Game: Snake 3D course.

When the snake dies, a Game Over panel comes up with a Play Again button. The panel is in the HUD and starts hidden, and SetActive(true) shows it. The snake knows when it dies, and the GameManager owns the screens, so Die() calls a public GameOver() on the GameManager.

Play Again starts over by loading the scene again. Every object comes back as the scene has it: the snake on its first cell with two segments, the score at 0, the panel hidden. A racing game's Retry button is wired the same way:

void Start()
{
    retryButton.onClick.AddListener(Retry);
}

void Retry()
{
    SceneManager.LoadScene("Track1");
}

Loading by name ties the button to one scene. SceneManager.GetActiveScene().buildIndex is the scene that is running, so loading it restarts whichever scene the button is in. The new scene has a new GameManager, whose Awake() sets Instance again, so the new snake talks to the new GameManager.

challenge icon

Challenge

Medium

Dying shows a Game Over panel, and Play Again starts a new game.

  1. In GameManager, add using UnityEngine.UI;, using UnityEngine.SceneManagement;, public GameObject gameOverPanel; and public Button playAgainButton;
  2. public void GameOver() shows the panel; void PlayAgain() loads the active scene again, and Start() adds it to playAgainButton.onClick.
  3. Snake's Die() calls GameManager.Instance.GameOver().

Press Play, crash and click Play Again: a new game starts. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Snake snake;
    public GameObject foodPrefab;
    public TMP_Text scoreText;
    private Transform food;
    private int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        scoreText.text = "Score: 0";
        food = Instantiate(foodPrefab).transform;
        MoveFood();
    }

    public bool IsFood(Vector3 cell)
    {
        return cell == food.position;
    }

    public void Eat()
    {
        score++;
        scoreText.text = "Score: " + score;
        MoveFood();
    }

    void MoveFood()
    {
        List<Vector3> free = new List<Vector3>();
        for (int x = -snake.edge; x <= snake.edge; x++)
        {
            for (int z = -snake.edge; z <= snake.edge; z++)
            {
                Vector3 cell = new Vector3(x, 0f, z);
                if (!snake.Occupies(cell))
                {
                    free.Add(cell);
                }
            }
        }
        food.position = free[Random.Range(0, free.Count)];
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Snake 3D

Practice on your own: Unity playground