unity 3 d:単一モード
6182 ワード
C#単例モード
///
/// C#
///
public abstract class Singleton where T : class,new()
{
private static T instance;
private static object syncRoot = new Object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new T();
}
}
return instance;
}
}
protected Singleton()
{
Init();
}
public virtual void Init() { }
}
MonoBehaviour単例
public class SingletonMono : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T Instance
{
get
{
if (applicationIsQuitting)
{
Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock (_lock)
{
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent();
singleton.name = string.Format("(singleton) {0}", typeof(T));
DontDestroyOnLoad(singleton);
}
return _instance;
}
}
set
{
if (_instance != null)
{
Destroy(value);
return;
}
_instance = value;
DontDestroyOnLoad(_instance);
}
}
public static bool applicationIsQuitting = false;
///
/// When Unity quits, it destroys objects in a random order.
/// In principle, a Singleton is only destroyed when application quits.
/// If any script calls Instance after it have been destroyed,
/// it will create a buggy ghost object that will stay on the Editor scene
/// even after stopping playing the Application. Really bad!
/// So, this was made to be sure we're not creating that buggy ghost object.
///
public virtual void OnDestroy()
{
applicationIsQuitting = true;
}
}