[Unity工具]查找GameObject在场景中所有被引用的地方

时间:2024-01-09 08:09:38

参考链接:

https://blog.csdn.net/hjzyzr/article/details/53316919?utm_source=blogxgwz4

https://blog.csdn.net/weixin_39706943/article/details/80507276

0.场景如下:

[Unity工具]查找GameObject在场景中所有被引用的地方

1.获取场景中所有的Go,包括嵌套的,隐藏的。需要注意的是要进行go.scene.name != null,这句判断,否则会包含很多来自其他地方的go(不只是来自Project视图)

 using UnityEngine;
using UnityEditor; /// <summary>
/// 查找GameObject在场景中所有被引用的地方
/// </summary>
public class FindGoInScene { [MenuItem("GameObject/FindGoInScene", priority = )]
static void Init()
{
GameObject[] goes = Resources.FindObjectsOfTypeAll<GameObject>();
for (int i = ; i < goes.Length; i++)
{
GameObject go = goes[i];
if (go.scene.name != null)
{
Debug.Log(go.name);
}
}
}
}

输出如下:

[Unity工具]查找GameObject在场景中所有被引用的地方

2.查找引用

TestFindGoInScene.cs

 using UnityEngine;

 public class TestFindGoInScene : MonoBehaviour {

     public GameObject temp;
}

FindGoInScene.cs

 using UnityEngine;
using UnityEditor;
using System.Reflection; /// <summary>
/// 查找GameObject在场景中所有被引用的地方
/// </summary>
public class FindGoInScene { [MenuItem("GameObject/FindGoInScene", priority = )]
static void Init()
{
GameObject[] goes = Resources.FindObjectsOfTypeAll<GameObject>();
for (int i = ; i < goes.Length; i++)
{
GameObject go = goes[i];
if (go.scene.name != null)
{
if (go != Selection.activeGameObject)
{
//Debug.Log(go.name);
Find(go);
}
}
}
} static void Find(GameObject go)
{
Component[] components = go.GetComponents<Component>();
for (int i = ; i < components.Length; i++)
{
Component component = components[i];
FieldInfo[] fields = component.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
for (int j = ; j < fields.Length; j++)
{
var value = fields[j].GetValue(component);
if (value == (object)Selection.activeGameObject)
{
Debug.LogWarning(go.name);
}
}
}
}
}

输出如下:

[Unity工具]查找GameObject在场景中所有被引用的地方