Updating a MonoBehavior into a persistent singleton
Imagine you are building a platforming game where the player collects items through multiple levels. Your team lead asks you to create a manager script to track the player’s score, handle scene transitions, and ensure there’s always one unique instance in a scene. Our first task is to ensure that the game manager class in the starter project only ever has one active instance.
Open Manager.cs
and update the code to match the following code, which sets the singleton instance or destroys the GameObject
that the script is attached to if an instance already exists:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Manager : MonoBehaviour
{
// 1
public static Manager Instance;
public int score = 0;
public int startingLevel = 1;
// 2
void Awake()
{
// 3
if(Instance...