Hi there,
I’m creating a custom editor for a platform object (like the MovingPlatformEditor in the 2DGameKit created by the Unity team).
I’ve added some editors for some properties (string, int, float) in the way they did in the 2DGameKit and it works as expected.
However when I try to create a popup for an enum in the same way they did it doesn’t work as expected. Here is the code I wrote identical to the code in 2DGameKit and I realized that most of the time when I change the value in the popup it changes to the value I’ve selected but when I run the game the value is restored to the previous one. The same happen in the 2DGameKit when I try to change the value in the popup.
Here’s the class with the apparent bug:
[CustomEditor(typeof(PlatformMoving))]
public class PlatformMovingEditorUnityVersion : Editor
{
PlatformMoving _target;
void OnEnable()
{
_target = target as PlatformMoving;
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
Looping looping = (Looping)EditorGUILayout.EnumPopup("Looping", _target.looping);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed Moving Platform type");
_target.looping = looping;
}
}
}
However I was watching the tutorial of the Adventure Game (the tutorial created by Unity team) and there they use another approach to create the custom editor. Here they use SerializedProperty and in this way it works as expected all the time.
Here’s the class implemented with that approach:
[CustomEditor(typeof(PlatformMoving))]
public class PlatformMovingEditorMyVersion : Editor
{
SerializedProperty looping;
void OnEnable()
{
looping = serializedObject.FindProperty("looping");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(looping, new GUIContent("Looping"));
serializedObject.ApplyModifiedProperties();
}
}
public enum Looping
{
Once = 1,
BackAndForth,
}
- Can anyone please tell me why there are two approaches to handle the properties in custom editors?
- What are the differences between those implementations?
- What is the recommended way to implement the custom editor?
Thanks.