Search code examples
unity-game-engineunity-editor

Unity Editor script to fill a serialized array with children of a specified GameObject


I have a serialized field of 'GameObject' that I would like to have automatically filled with children of a game object I want to specify manually.

Bonus points if I can make it impossible to manually change this array on the component, but to only display it in a 'grayed out' state.

Is this operation possible? Thanks in advance.


Solution

  • Solution:

    [CustomEditor( typeOf( ClassYouWantToManage ) )]
    class ClassYouWantToManageEditor
    {
      ClassYouWantToManage value;
    
      void OnEnable()
      {
       // target is the upcasted version of your managed class
       value = (ClassYouWantToManage) target;
      }
    
      public override void OnInspectorGUI()
      {
        // specifiedObject is the 'parent', with whos children you want to populate the array. has to be public
        if (value.specifiedObject == null)
        {
          throw new Exception ("Specified object is null");
        }
    
        // targetArray is the array you want to populate with children. has to be public
        // simple population alg
        value.targetArray = new GameObject[specifiedObject.transform.ChildCount];
        for (int i = 0; i < specifiedObject.transform.ChildCount; i++)
        {
          value.targetArray[ i ] = specifiedObject.transform.GetChild( i ).gameObject;
        } 
      }
    }