Unity Editor 脚本用指定游戏对象的子项填充序列化数组

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

我有一个 'GameObject' 的序列化字段,我想自动填充我想手动指定的游戏对象的子对象。

奖励积分,如果我可以使无法在组件上手动更改此数组,而是仅以 'grayed out' 状态显示它。

这个操作可以吗?提前致谢。

有帮助吗?

GameObject[] myArray;
GameObject parent;

void GetChildren()
{

    myArray=new GameObject[parent.transform.childCount];
    for (int i=0;i<parent.transform.childCount;i++)
    myArray[i]=parent.transform.GetChild(i).gameObject;

}

至于以不可编辑的状态显示它 - 这是可能的,但需要为该组件编写自定义编辑器/检查器。

解决方案:

[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;
    } 
  }
}