查找丢失组件的预制体

      在制作游戏的过程中,我们经常会遇到预制体丢失组件的情况,如下图所示。

      预制体丢失组件,一般情况下如果我们不去获取该组件,就不会报错或影响游戏的运行。但是在游戏加载该预制体时,会报警告,看到Console中有警告的话也是非常难受的。考虑到游戏中使用了上百的预制体,每个预制体又由数个甚至数十个子物体组成,手动寻找丢失组件的预制体的工作量太大,不具有很好的可操作性。

      有没有方法可以获取丢失组件的预制体呢?答案是有的。

    (1)获取游戏中的所有的预制体

 1     public static string[] GetAllPrefabs()
 2     {
 3         string[] temp = AssetDatabase.GetAllAssetPaths();
 4         List<string> result = new List<string>();
 5         foreach (string s in temp)
 6         {
 7             if (s.Contains(".prefab")) result.Add(s);
 8         }
 9         return result.ToArray();
10     }

GetAllPrefabs()方法首先使用AssetDatabase.GetAllAssetPaths()获取所有的资源的路径名;然后遍历所有的资源路径,找出包含“.prefab”的路径(即是预制体);返回所有预制体的路径名的数组。

     (2)查找丢失了组件的预制体

 1                     string[] allPrefabs = GetAllPrefabs();
 2                     listResult = new List<string>();
 3                     foreach (string prefab in allPrefabs)
 4                     {
 5                         UnityEngine.Object o = AssetDatabase.LoadMainAssetAtPath(prefab);
 6                         GameObject go;
 7                         try
 8                         {
 9                             go = (GameObject)o;
10                             Component[] components = go.GetComponentsInChildren<Component>(true);
11                             foreach (Component c in components)
12                             {
13                                 if (c == null)
14                                 {
15                                     listResult.Add(prefab);
16                                 }
17                             }
18                         }
19                         catch
20                         {
21                             Debug.Log("For some reason, prefab " + prefab + " won't cast to GameObject");
22                         }
23                     }

     使用foreach循环遍历上面获得的所有的预制体的路径名。对每一个预制体路径名,首先使用AssetDatabase.LoadMainAssetAtPath(prefab)方法加载该资源,然后将加载后的资源转化为GameObject类型的对象。接下来,使用go.GetComponentsInChildren<Component>(true)获取go的所有child的Component。这里有一点要注意的是public T[] GetComponentsInChildren<T>(bool includeInactive)方法的参数includeInactive要设为true,意思是包括非激活状态的对象。最后一步,如果一个组件丢失的话,获得的组件值为null。遍历一个物体上面的所有组件,找到为null的,即为丢失的组件。

     主要的方法就是上面的这些。当然在我们的实际工作学习过程中,可以将上面的方法做成一个插件,方便使用。

原文地址:https://www.cnblogs.com/bzyzhang/p/6485918.html