public abstract class DataCenter<T> : MonoBehaviour where T : MonoBehaviour
{
private static string rootName = "DataCenter";
private static GameObject gameDataCenter;
private static T instance;
public static T Instance
{
get
{
if (gameDataCenter == null)
{
gameDataCenter = GameObject.Find(rootName);
if (gameDataCenter == null) Debug.Log("please create a gameobject named " + rootName);
}
if (instance == null)
{
instance = gameDataCenter.GetComponent<T>();
if (instance == null) instance = gameDataCenter.AddComponent<T>();
}
return instance;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例存储
/// </summary>
public class GameCenter : DataCenter<GameCenter>
{
void Start()
{
}
void Update()
{
}
}
常用单例02
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DataCenter
{
private static DataCenter _instance;
private static readonly object syncRoot=new object();
private DataCenter()
{
}
public static DataCenter Instance()
{
if (_instance==null)
{
lock (syncRoot)
{
if (_instance == null)
{
_instance=new DataCenter();
}
}
}
return _instance;
}
}