Custom editor object field getting serialized object

Hi!

I am trying to make a custom editor for my weapons but then I get some problems with the projectile field. The projectile is basically just a GameObject. This is a very basic breakdown of my script.

public SerializedProperty projectile_Prop;

void OnEnable()
    {
        projectile_Prop = serializedObject.FindProperty("projectile");
    }

public override void OnInspectorGUI()
{
        serializedObject.Update();
        projectile_Prop = EditorGUILayout.ObjectField(projectile_Prop, typeof(Object), true);

        serializedObject.ApplyModifiedProperties();
}

Okay, this took some digging - the serialized stuff is kinda a pain to understand, but seems nice when you know it.

So, what you have to do is to wrap your target object(s) in a SerializedObject, and then find the serialized property on that - it seems like you’ve done that. Then, you use PropertyField to change the value. I got this to work:

SerializedProperty projectile_Prop;

void OnEnable() {
    projectile_Prop = serializedObject.FindProperty("projectile");
}

public override void OnInspectorGUI() {
    serializedObject.Update();
    EditorGUILayout.PropertyField(projectile_Prop);
    serializedObject.ApplyModifiedProperties();
}

That allows me to assign different things to the field ‘public GameObject projectile’ on the script that this script is the editor for. PropertyField draws the correct layout depending on the kind of field you’re looking at, so that’s nice.

Hope that helps!