Skip to content

Instantly share code, notes, and snippets.

@jscMR
Created July 29, 2020 08:00
Show Gist options
  • Select an option

  • Save jscMR/e1d866b52f6e788eae70a7a0b858e0d5 to your computer and use it in GitHub Desktop.

Select an option

Save jscMR/e1d866b52f6e788eae70a7a0b858e0d5 to your computer and use it in GitHub Desktop.

Revisions

  1. jscMR created this gist Jul 29, 2020.
    14 changes: 14 additions & 0 deletions singleton.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
    {
    private static readonly Lazy<T> LazyInstance = new Lazy<T>(CreateSingleton);

    public static T Instance => LazyInstance.Value;

    private static T CreateSingleton()
    {
    var ownerObject = new GameObject($"{typeof(T).Name} (singleton)");
    var instance = ownerObject.AddComponent<T>();
    DontDestroyOnLoad(ownerObject);
    return instance;
    }
    }
    4 changes: 4 additions & 0 deletions using.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    public class GameManager : Singleton<GameManager>
    {
    ...
    }