Singleton script for GameObject permanence

Hi guys, I noticed in the 2D tutorial we keep adding a DontDestroyOnLoad singleton to individual scripts, and thought it might be tidier to just write a standalone component for it. It’s pretty simple, just makes sure there’s only ever one GameObject with the given name and the Singleton component attached.

I’m sure it’s been done before but thought I’d share. If you can think of any improvements let me know!

using System.Collections.Generic;
using UnityEngine;

static class SingletonManager
{
  public static List<string> singletonNames = new List<string>{};
  public static void AddName(string name)
  {
    SingletonManager.singletonNames.Add(name);
  }
  public static bool HasName(string name)
  {
    return SingletonManager.singletonNames.Contains(name);
  }
}


class Singleton : MonoBehaviour
{
  private void Awake()
  {
    var singletonName = gameObject.name;

    if (SingletonManager.HasName(singletonName))
    {
      Destroy(this.gameObject);
    }
    else
    {
      SingletonManager.AddName(singletonName);
      DontDestroyOnLoad(gameObject);
    }
  }
}

Privacy & Terms