- Home /
Editor.CreateEditor returns null for an object type with a custom editor
So I'm working on a custom editor for an object that essentially stores a list of other objects. The idea is to make a bunch of foldouts (dropdowns) in the inspector that show the custom inspector for each object in the list.
The custom editor code for the storage object looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(StorageSystem))]
public class StorageSystemPropertyDrawer : Editor
{
List<Editor> itemEditors = new List<Editor>();
List<bool> foldouts = new List<bool>();
private void OnEnable()
{
if(itemEditors.Count == 0)
{
foldouts.Clear();
StorageSystem system = (StorageSystem)target;
foreach (Item item in system.items)
{
storageEditors.Add(Editor.CreateEditor(item));
foldouts.Add(false);
}
}
}
public override void OnInspectorGUI()
{
StorageSystem system = (StorageSystem)target;
for (int b = 0; b < system.items.Count; b++)
{
foldouts[b] = EditorGUILayout.Foldout(foldouts[b], system.items[b].itemName);
if(foldouts[b])
{
itemEditors[b].OnInspectorGUI();
if (GUI.changed)
EditorUtility.SetDirty(target);
}
}
if (GUILayout.Button("Add Item"))
{
system.items.Add(new Item());
Debug.Log(typeof(ItemEditor));
itemEditors.Add(Editor.CreateEditor(system.items[system.items.Count - 1]) as ItemEditor);
foldouts.Add(false);
}
if (GUILayout.Button("Clear Items"))
{
system.items.Clear();
itemEditors.Clear();
foldouts.Clear();
}
}
}
And the custom editor for the actual items:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;
[CustomEditor(typeof(Item))]
public class ItemEditor : Editor
{
public override void OnInspectorGUI()
{
//Unimportant implementation stuff
}
}
So the issue lies in the fact that this code causes a NullReferenceException at the following line:
itemEditors[b].OnInspectorGUI();
Through some debugging, it appears that the actual itemEditor is null, despite the fact that a CustomEditor exists for the Item type. Any ideas as to why this might be happening?
Answer by JamesGameDev · Mar 27, 2020 at 12:58 AM
Turns out the Item class was a Monobehavior and needed to be a ScriptableObject. Changed it and it works now.