unity 单例
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class BaseWindow<T> : MonoBehaviour where T : MonoBehaviour
{
static T instance;
public static T Instance
{
get
{
if (instance == null)
{
// 先在场景中找寻
List<T> ts = Skode_GetTObjs<T>();
// 场景中找不到就报错
if (ts.Count == 0)
{
Debug.Log("该场景找不到该脚本:" + typeof(T));
return instance;
}
instance = ts[0];
if (ts.Count > 1)
{
foreach (var VARIABLE in ts)
{
Debug.Log("场景存在多个" + VARIABLE, VARIABLE.gameObject);
}
}
}
return instance;
}
}
/// <summary>
/// 获取场景中带有T组件的所有物体
/// </summary>
public static List<T> Skode_GetTObjs<T>() where T : MonoBehaviour
{
List<T> objectsInScene = new List<T>();
//该方法会连带预制体一起查找。因此gameObject.scene.name可过滤掉预制体
foreach (T go in Resources.FindObjectsOfTypeAll<T>().ToList())
{
if (!(go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave ||
go.gameObject.scene.name == null))
objectsInScene.Add(go);
}
return objectsInScene;
}
}
用法
public class Test : BaseWindow<Test>
{
}
原文地址:https://blog.csdn.net/weixin_38239050/article/details/117066912?spm=1001.2014.3001.5501