Object references in a custom editor

I am writing a custom editor for an object. That custom editor is for a class which should essentially be able to store a varying number of dynamic persistent references to assets and scene objects on it. Imagine a “PrefabsLinker” script, which can be attached to objects in the Editor and let users link prefabs to it.

Drawing the ObjectFields to display and let the user choose the assets is easy, and so is keeping them for the “current session”. Basically, it is enough to, for each dynamic field:

mField = EditorGUILayout.ObjectField(mField, typeof(UnityEngine.Object), true);

However, I am not sure what would be the best way to persist the choice. The problem is that though I can choose an object for the mField, when Unity is restarted the choice is forgotten. In fact, I guess that if I were to export the project, the specific asset that I referenced wouldn’t necessarily be exported.

It is my (limited) understanding that through SerializedProperties I would be able to do this with relative ease, but I don’t think I can rely on SerializedProperties at all, because I need to create those references dynamically (sometimes there will be 3 references in the object, sometimes 5, sometimes more…).

How could I do this?

If Unity looses the changes upon restart, mField probably is not serialized. If mField is of type UnityEngine.Object make sure it is either public or has the [SerializeField] attribute.

Using SerializedProperties should work just fine. If you want to store multiple objects just use an array:

//In your object
Object[] myObjects;

//In editor with SerializedObject propObject
public override void OnInspectorGUI(){
    propObject.FindProperty("myObjects").arraySize = 5;
    for(int i = 0; i < propObject.FindProperty("myObjects").arraySize; i++)
        SerializedProperty currentObject = propObject.FindProperty("myObjects").GetArrayElementAtIndex(i);
        currentObject.objectReferenceValue =  EditorGUILayout.ObjectField(currentObject.objectReferenceValue, typeof(UnityEngine.Object), true);

I use scriptable objects to store in a list on an empty gameobject that acts as the manager. You can store anything in there pretty much. Not what you asked for but it might help.

I can provide an example if you want but probably more honest to show where I got the idea from!

[SpellMaker on YouTube][1]

The unity package is downloadable on that page so you can see how it works.
[1]: Spell Maker - Unity 3d package - YouTube