1、单例类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T:Singleton<T>
{
private static T instance;
public static T Instance
{
get { return instance; }
}
protected virtual void Awake()
{
if(instance!=null)
{
Destroy(gameObject);
}else
{
instance = (T)this;
}
}
public static bool IsInitialized
{
get { return instance != null; }
}
protected virtual void OnDestroy()
{
if(instance==this)
{
instance = null;
}
}
}
2、使用方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonTest : Singleton<SingletonTest>
{
//Awake不能忘
protected override void Awake()
{
base.Awake();
}
public void DeblogHolldAR()
{
Debug.Log("HolldAR");
}
//OnDestroy不能忘
protected override void OnDestroy()
{
base.OnDestroy();
}
}
3、调用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectRoatation : MonoBehaviour
{
private void Start()
{
//调用
SingletonTest.Instance.DeblogHolldAR();
}
}
4、打印