using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SingletonTemplate<T>: MonoBehaviour where T: MonoBehaviour
{
private static T instance;
public static T GetInstance
{
get
{
if (instance == null)
{
T[] instances = FindObjectsOfType<T>();
if (instances!=null)
{
for (var i = 0; i < instances.Length; i++)
{
Destroy(instances[i].gameObject);
}
}
GameObject go = new GameObject();
go.name = typeof(T).Name;
instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
return instance;
}
}
using System.Collections;
using System.Collections.Generic;
public class SingletonTemplate<T>: MonoBehaviour where T: MonoBehaviour
{
private static T instance;
public static T GetInstance
{
get
{
if (instance == null)
{
T[] instances = FindObjectsOfType<T>();
if (instances!=null)
{
for (var i = 0; i < instances.Length; i++)
{
Destroy(instances[i].gameObject);
}
}
GameObject go = new GameObject();
go.name = typeof(T).Name;
instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
return instance;
}
}
}
using UnityEngine;
using System.Collections;
public class MySingleton : SingletonTemplate<MySingleton>
{
void Start()
{
Debug.Log(111111111111);
}
public void Task()
{
Debug.Log(55555555555);
}
}
using UnityEngine;
using System.Collections;
public class MyTest : MonoBehaviour {
// Use this for initialization
void Start () {
MySingleton.GetInstance.Task();
}
}