单例

/*
*FileName: MonoSingleton.cs
*Author: AUTHOR
*Date: 2023/08/15 13:12:41
*UnityVersion: 2021.3.15f1c1
*Description:
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Mono单例类
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _singleton;

public static T SingleTon
{
get
{
if (_singleton == null)
{
_singleton = FindObjectOfType<T>();
if (_singleton == null)
{
Debug.LogError("场景中未找到类的对象,类名为:" + typeof(T).Name+"该类可能没有挂载到场景中");
}
}
return _singleton;
}
}

private void Awake()
{
if (_singleton == null)
{
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}

posted @ 2023-08-18 18:48  Trigger_F  阅读(6)  评论(0)    收藏  举报