r/UnityHelp • • Jun 08 '23

How to make enum-driven CustomEditor that allows me to drag prefabs to each field, and get them in code?

I've gotten this much:

using UnityEngine;
using UnityEditor;

namespace Creatures
{
	[CustomEditor(typeof(CreatureSpawner))]
	public class CreatureSpawnerEditor : Editor
	{
		public override void OnInspectorGUI()
		{
			serializedObject.Update();

			CreatureSpawner creatureSpawner = (CreatureSpawner)target;

			foreach (CreatureLookup.CreatureTypes creatureType in System.Enum.GetValues(typeof(CreatureLookup.CreatureTypes)))
			{
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField(creatureType.ToString(), GUILayout.Width(100));
				EditorGUILayout.ObjectField(null, typeof(GameObject), false);
				EditorGUILayout.EndHorizontal();
			}

			serializedObject.ApplyModifiedProperties();
		}
	}
}

It got me really excited to see the creature types showing up! However, I have absolutely no idea how to get these values OUT. How do I use them from my CreatureSpawner code? I want to be able to call SpawnCreature(creatureType) and have it instantiate the prefab assigned in the editor.

3 Upvotes

6 comments sorted by

1

u/nulldiver Jun 08 '23

At this point, you’re not serializing anything, just drawing UI for the object fields. You need to assign those values back to something serialized in the spawner until then, there is nothing to get out.

1

u/planetidiot Jun 08 '23

Right, but how? I tried some code from ChatGPT but it doesn't work. It was having me serialize a Dictionary, then had me create a custom SerializeableDictionary but nothing worked. I'm out of my element here, I've only ever worked on the "normal" game object scripts, not these custom editor things. Every time I've tried, it breaks and I give up.

1

u/nulldiver Jun 08 '23

This is the normal part now. You want to serialize a Dictionary that has enum keys and object references for your prefabs. The only curveball is that Unity doesn’t serialize Dictionaries, which isn’t related at all to the editor UI stuff. There are different approaches you could take. A serializable Dictionary is one, but if your enum is just for convenience and integer values are sequential, probably serializing a List and having the index be the integer value of the enum is the simplest. It all depends on how you’re going to access it, etc.

The editor UI stuff just needs to use the return value of the object field to assign into whatever you decide to use.

1

u/planetidiot Jun 08 '23

Thanks, I went down that road and couldn't crack it. I think I've hit my limit on this and I just don't get it. I'm going to use the public Generic List approach and move on.

1

u/nulldiver Jun 08 '23 edited Jun 08 '23

Ok, so lets say you have an enum:

public enum ExampleEnum{One,Two,Three,Four}

And you want something that lets you do like Something[ExampleEnum.One] = myGameObject so that you can spawn that, show it in the UI, etc. but you can't serialize a Dictionary. The simplest structure is probably just some backing lists. Something like this:

[Serializable]public class EnumObject: IEnumerable{
[SerializeField]
private List<SimpleExample.ExampleEnum> enumList = new();
[SerializeField]
private List<GameObject> gameObjectList = new();

public EnumObject()
{
enumList = Enum.GetValues(typeof(SimpleExample.ExampleEnum)).Cast<SimpleExample.ExampleEnum>().ToList();
gameObjectList = new List<GameObject>(enumList.Count);
}

public GameObject this[SimpleExample.ExampleEnum index]
{
get => gameObjectList[(int) index];
set => gameObjectList[(int) index] = value;
}
public IEnumerator GetEnumerator() => enumList.GetEnumerator();}

With the rather huge qualifier that I'm doing absolutely nothing there to handle what happens when you change the size or contents of your enum after it is made (oh, and I'm writing this in a comment on reddit so it may totally not run as-is) So you've got something like:

public class SimpleExample : MonoBehaviour
{
/// the enum is here but could be wherever...
[SerializeField]
public EnumObject enumObject = new();
}

So, cool... now we are serializing that custom class. We can instantiate enumObject[ExampleEnum.Two] or whatever. Now we want UI... You can use SerializedProperties or whatever you want, but the key is that you want to not just display the objects, but save changes back to what we are serializing. So you would have something like:

[CustomEditor(typeof(SimpleExample))]
public class SimpleExampleInspector : Editor{
public override void OnInspectorGUI(){
var simpleExample = (SimpleExample)target;
foreach (SimpleExample.ExampleEnum exampleEnum in simpleExample.enumObject){
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(exampleEnum.ToString(), GUILayout.Width(100));
EditorGUI.BeginChangeCheck();
simpleExample.enumObject[exampleEnum] = (GameObject)EditorGUILayout.ObjectField(simpleExample.enumObject[exampleEnum], typeof(GameObject), false);
if (EditorGUI.EndChangeCheck()){
EditorUtility.SetDirty(simpleExample);
}
EditorGUILayout.EndHorizontal();
}
}
}

I hope that makes sense? Edit: Looks like my code got hopelessly mangled. I tried to fix it. Sorry.

1

u/planetidiot Jun 08 '23 edited Jun 08 '23

Big Edit 2:

ChatGPT helped me get the error fixed. Then I added a button to remove the empty enums if I delete one and there's orphaned valued. Here's the updated code, and I think it works!

As for deleting an enum and adding a new one (delete ExampleEnum.Two and add ExampleEnum.Five) causes them to shift places, which is fine, I can easily see if they go out of order. The odd thing is if I delete one and don't add a new one, so delete ExampleEnum.Three, Four takes it's place and I get an int value at the end of the list "3" which holds the old Four game object. This is what the "Remove Empty" button gets rid of, and is should do just fine, assuming I'm not missing something! Thanks again!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

[Serializable]
public class EnumObject : IEnumerable
{
	[SerializeField]
	private List<SimpleExample.ExampleEnum> enumList = new List<SimpleExample.ExampleEnum>();
	[SerializeField]
	private List<GameObject> gameObjectList = new List<GameObject>();

	public EnumObject()
	{
		enumList = Enum.GetValues(typeof(SimpleExample.ExampleEnum)).Cast<SimpleExample.ExampleEnum>().ToList();
		gameObjectList = new List<GameObject>(enumList.Count);

		// Initialize gameObjectList with null values
		for (int i = 0; i < enumList.Count; i++)
		{
			gameObjectList.Add(null);
		}
	}

	public GameObject this[SimpleExample.ExampleEnum index]
	{
		get => gameObjectList[(int)index];
		set => gameObjectList[(int)index] = value;
	}

	public void RemoveEmpties()
	{
		enumList = Enum.GetValues(typeof(SimpleExample.ExampleEnum)).Cast<SimpleExample.ExampleEnum>().ToList();
		if (enumList.Count < gameObjectList.Count)
		{
			int diff = gameObjectList.Count - enumList.Count;

			gameObjectList.RemoveRange(gameObjectList.Count - diff - 1, diff);
		}
	}

	public IEnumerator GetEnumerator() => enumList.GetEnumerator();
}

public class SimpleExample : MonoBehaviour
{
	public enum ExampleEnum { One, Two, Four }

	[SerializeField]
	public EnumObject enumObject = new EnumObject();

	private void Start()
	{
		GameObject.Instantiate(enumObject[ExampleEnum.One]);
		GameObject.Instantiate(enumObject[ExampleEnum.One]);
		GameObject.Instantiate(enumObject[ExampleEnum.One]);
		GameObject.Instantiate(enumObject[ExampleEnum.One]);
		GameObject.Instantiate(enumObject[ExampleEnum.One]);
	}
}

[CustomEditor(typeof(SimpleExample))]
public class SimpleExampleInspector : Editor
{
	public override void OnInspectorGUI()
	{
		var simpleExample = (SimpleExample)target;

		foreach (SimpleExample.ExampleEnum exampleEnum in simpleExample.enumObject)
		{
			EditorGUILayout.BeginHorizontal();
			EditorGUILayout.LabelField(exampleEnum.ToString(), GUILayout.Width(100));
			EditorGUI.BeginChangeCheck();
			simpleExample.enumObject[exampleEnum] = (GameObject)EditorGUILayout.ObjectField(simpleExample.enumObject[exampleEnum], typeof(GameObject), false);
			if (EditorGUI.EndChangeCheck())
			{
				EditorUtility.SetDirty(simpleExample);
			}
			EditorGUILayout.EndHorizontal();

		}
		if (GUILayout.Button("Remove Empty"))
		{
			// Call the empty method for Remove button
			simpleExample.enumObject.RemoveEmpties();
		}
	}
}