单例基类
使用单例模式,可以随时在脚本中调用管理器中的属性和方法。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Common
{
/// <summary>
/// 单例基类
/// </summary>
public class MonoSingleton<T> : MonoBehaviour where T:MonoSingleton<T>
{
private static T instance;
public static T Instance {
get
{
if(instance == null)
{
instance = FindObjectOfType<T>();
if(instance == null)
{
new GameObject("Singleton of " + typeof(T)).AddComponent<T>();
}
else
{
instance.Init();
}
}
return instance;
}
}
public void Awake()
{
if(instance == null)
{
instance = this as T;
Init();
}
}
public virtual void Init()
{
}
}
}
单例子类
namespace Common
{
/// <summary>
/// XX管理器
/// </summary>
public class XXManger : MonoSingleton<XXManger>
{
public string Log { get; set; }
public void Fun1()
{
print(Log);
}
public override void Init()
{
base.Init();
Log = "fun1";
}
}
}
脚本调用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Common;
namespace Test
{
/// <summary>
///
/// </summary>
public class Test : MonoBehaviour
{
private void Awake()
{
XXManger.Instance.Fun1();
}
}
}