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;
public class GameDataCenter : DataCenter<GameDataCenter>
{
public RoboticArmRotate RoboticArmRotate;
public UIButtonCenter UIButtonCenter;
public GrabObject GrabObject;
public LaserPointer_Chh LaserPointerChh;
public GameCenterManager GameCenterManager;
public Animator WheelAnimator;
public InstantiationObject InstantiationObject;
public bool IsGrab=false;
void Start()
{
}
void Update()
{
}
}
第二种 防止多个线程创建 用了双If+lock
public class Singleton
{
private static Singleton _Instance = null;
private static object Instance_Lock = new object();
public static Singleton Instance()
{
if (_Instance == null) //双if +lock
{
lock (Instance_Lock )
{
if (_Instance == null)
{
_Instance = new Singleton();
}
}
}
return _Instance;
}
}