Let’s say I have a MonoBehavior called Unit in an RPG, and he has a list of Move MonoBehaviors.
When editing the list in the Unit component in the Inspector, I would like to be able to edit the attributes of each Move in said list, in nested fashion in the Inspector. I would like to know how to achieve this. The goal is to have a neatly organized Inspector for Unit with its nested and modifiable Move MonoBehaviors. MonoBehaviors within MonoBehaviors, basically.
The easiest thing is to create an editor for the nested monobehaviour, and call that editor’s OnInspectorGUI:
[CustomEditor(typeof(TestScript))]
public class TestScriptEditor : Editor {
private TestScript parentBehaviour;
private Editor[] childEditors;
void OnEnable() {
parentBehaviour = (TestScript) target;
childEditors = new Editor[parentBehaviour.childBehaviours.Count];
for (int i = 0; i < childEditors.Length; i++) {
childEditors[i] = Editor.CreateEditor(parentBehaviour.childBehaviours[i]);
}
}
public override void OnInspectorGUI() {
base.OnInspectorGUI();
foreach (var editor in childEditors) {
editor.OnInspectorGUI();
}
// This needs to happen after the editors are drawn! OnInspectorGUI is called twice, once for
// layout, another for actually drawing the things and taking input. If you do this before drawing the
// sub inspectors, and add/remove sub inspectors, the number of inspectors drawn in the layout and
// drawing phases are different, and Unity starts puking error messages in the console.
childEditors = new Editor[parentBehaviour.childBehaviours.Count];
for (int i = 0; i < childEditors.Length; i++) {
childEditors[i] = CreateEditor(parentBehaviour.childBehaviours[i]);
}
}
}
I’ll let you handle proper indentation and only updating the list of editors yourself.
Alternately - make your Move class not inherit from MonoBehaviour, decorate it with [Serializable] and the inspector will take care of itself (to an extent).