Search Unity

Editor scripting question (accessing SerializeFields on objects in asset library)

Discussion in 'Editor & General Support' started by ccklokwerks, Jun 7, 2019.

  1. ccklokwerks

    ccklokwerks

    Joined:
    Oct 21, 2014
    Posts:
    62
    Hi all,

    I have recently written some editor scripts for myself to find old Text scripts (to replace them with TextMeshPro), and to find null components because scripts have been deleted.

    I would really like to be able to select a prefab in the project and then get a list of the other prefabs (or scenes) which reference it.

    I'm familiar with how to iterate through the project's assets and screen out just the prefabs (assuming they have the extension .prefab) and then through the Components on the objects in the prefab. But I then need to access the SerializeFields for each prefab (phew!) and that is where I'm stuck. Can anyone fill me in?

    Thanks!

    P.S. here is my "find null components" code in case anyone finds it useful. Or maybe I'm doing something bad with the load call; not sure if I need to do anything to dispose of them but I presume not.

    Code (CSharp):
    1.     [MenuItem("Tools/Find Null Scripts")]
    2.     static void FindNullScripts()
    3.     {
    4.         foreach (string s in AssetDatabase.GetAllAssetPaths())
    5.         {
    6.             if (!s.EndsWith(".prefab", System.StringComparison.CurrentCulture))
    7.             {
    8.                 continue;
    9.             }
    10.             GameObject obj = AssetDatabase.LoadAssetAtPath(s, typeof(GameObject)) as GameObject;
    11.             if (obj == null)
    12.             {
    13.                 continue;
    14.             }
    15.             Transform t = FindNullScript(obj.transform);
    16.             if (t != null)
    17.             {
    18.                 Debug.Log("Found missing script in " + s + " on " + t.name);
    19.             }
    20.         }
    21.     }
    22.  
    23.     static Transform FindNullScript(Transform t)
    24.     {
    25.         Component[] components = t.GetComponents<Component>();
    26.         for (int i = 0; i < components.Length; i++)
    27.         {
    28.             if (components[i] == null)
    29.             {
    30.                 return t;
    31.             }
    32.         }
    33.         for (int i = 0; i < t.childCount; ++i)
    34.         {
    35.             Transform badChild = FindNullScript(t.GetChild(i));
    36.             if (badChild)
    37.             {
    38.                 return badChild;
    39.             }
    40.         }
    41.         return null;
    42.     }