using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class BaseWindow : MonoBehaviour where T : MonoBehaviour
{
static T instance;
public static T Instance
{
get
{
if (instance == null)
{
// 先在场景中找寻
List ts = Skode_GetTObjs();
// 场景中找不到就报错
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;
}
}
///
/// 获取场景中带有T组件的所有物体
///
public static List Skode_GetTObjs() where T : MonoBehaviour
{
List objectsInScene = new List();
//该方法会连带预制体一起查找。因此gameObject.scene.name可过滤掉预制体
foreach (T go in Resources.FindObjectsOfTypeAll().ToList())
{
if (!(go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave ||
go.gameObject.scene.name == null))
objectsInScene.Add(go);
}
return objectsInScene;
}
}
用法
public class Test : BaseWindow
{
}
原文地址:https://blog.csdn.net/weixin_38239050/article/details/117066912?spm=1001.2014.3001.5501