Skip to content

Instantly share code, notes, and snippets.

@minhd
Created December 31, 2017 11:49
Show Gist options
  • Save minhd/b5c067e50612797e46ae9baf6d7ed216 to your computer and use it in GitHub Desktop.
Save minhd/b5c067e50612797e46ae9baf6d7ed216 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour where T : Component {
private static T instance;
public static T Instance {
get {
if (instance == null) {
instance = FindObjectOfType<T>();
if (instance == null) {
GameObject obj = new GameObject();
obj.name = typeof(T).Name;
instance = obj.AddComponent<T>();
}
}
return instance;
}
}
protected virtual void Awake() {
if (instance == null) {
instance = this as T;
Init();
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
}
public abstract void Init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment