- Home /
Events in custom inspector
I'm trying to write a custom inspector that includes some UnityEvents. So far I've gotten a UnityEvent to display in the inspector using the following code (appropriate using tags not shown):
public class InteractionManager : MonoBehaviour
{
public UnityEvent onInteract;
}
[CustomEditor(typeof(InteractionManager))]
public class InteractionEditor : Editor
{
public override void OnInspectorGUI()
{
InteractionManager interaction = (InteractionManager)target;
serializedObject.Update();
EditorGUILayout.PropertyField(new SerializedObject(interaction).FindProperty("onInteract"));
serializedObject.ApplyModifiedProperties();
}
}
but I can't edit the event. Every other forum post I've read says to add serializedObject.Update();
at the beginning and serializedObject.ApplyModifiedProperties();
at the end like I've done here in order to edit the event, but for me it didn't change anything. What am I doing wrong?
Answer by Bunny83 · Jun 21, 2020 at 04:00 PM
You made a major mistake here. The "SerializedObject" class is there to wrap the actual serialized data. It actually contains SerializedProperty instances for every value that is stored in the data. A custom editor has the serializedObject property (which you are actually using when you call Update and ApplyModifiedProperties). This SerializedObject is automatically created for the object your editor is "inspecting".
Your mistake is that you create a new SerializedObject instance for displaying your property. However the changes that the PropertyField applies are applied to the SerializedObject you just created. Since you never call "ApplyModifiedProperties" on that instance nothing will be saved. So instead of this:
EditorGUILayout.PropertyField(new SerializedObject(interaction).FindProperty("onInteract"));
you should do this:
EditorGUILayout.PropertyField(serializedObject.FindProperty("onInteract"));
Though for performance reasons it would be better to do something like this:
[CustomEditor(typeof(InteractionManager))]
public class InteractionEditor : Editor
{
SerializedProperty m_OnInteract;
void OnEnable()
{
m_OnInteract = serializedObject.FindProperty("onInteract");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(m_OnInteract);
serializedObject.ApplyModifiedProperties();
}
}