CangJie/Assets/Scripts//UnitySingleton.cs

41 lines
846 B
C#
Raw Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例模式类模板
/// </summary>
public class UnitySingleton<T> : MonoBehaviour
where T : Component
{
private static T m_instance;
public static T Instance
{
get
{
if (m_instance == null)
{
m_instance = FindObjectOfType<T>();
if (m_instance == null)
{
Debug.LogError("缺少 " + typeof(T) + " 这个单例,没法在场景中找到");
}
}
return m_instance;
}
}
protected virtual void Awake()
{
if (m_instance == null)
{
m_instance = this as T;
}
else
{
Destroy(gameObject);
}
}
}