Custom inspector resetting values on loss of focus/play

I’m working on a custom inspector that uses reflection to get a list of all my enemies and populates a popup dialogue with them. So far I have that much working and can select and spawn an enemy with the right name, but there’s a problem: as soon as I hit play or take focus away from the gameobject with the custom inspector, the value from the dropdown resets.

Here’s the inspector code:

[CustomEditor(typeof(EnemyFactory))]
public class EnemyFactoryEditor : Editor
{
    int _choiceIndex = 0;
    string[] inspectorChoices = new string[0];
    List <System.Type> listOfDerivedClasses = Assembly.GetExecutingAssembly ().GetTypes ().Where (x => x.IsSubclassOf (typeof(Enemy))).ToList ();

    public override void OnInspectorGUI ()
    {
        EnemyFactory targetFactory = (EnemyFactory)target;

        inspectorChoices = new string[listOfDerivedClasses.Count];

        for (int i = 0; i < listOfDerivedClasses.Count; i++) {
            inspectorChoices [i] = listOfDerivedClasses [i].Name.ToString ();
        }

        DrawDefaultInspector();
        EditorGUILayout.LabelField ("Enemy type:");
        _choiceIndex = EditorGUILayout.Popup(_choiceIndex, inspectorChoices);

        targetFactory.selectedEnemy = _choiceIndex;

        EditorUtility.SetDirty(target);
    }
}

And here’s the factory code so far (I still need to get a handle on how to spawn enemies of the right type)

public class EnemyFactory : MonoBehaviour {

    public float healthPoints = 100;
    public int healthNotches = 0;
    public float speed = 0;
    public float acceleration = 0;

    [HideInInspector]
    public int selectedEnemy;

    void Awake () {
        var type = typeof(Enemy);

        var listOfDerivedClasses = Assembly.GetExecutingAssembly ().GetTypes ().Where (x => x.IsSubclassOf (type)).ToList ();

        for (int i = 0; i < listOfDerivedClasses.Count; i++) {
//            Debug.Log (listOfDerivedClasses [i].Name.ToString ());
        }

        Debug.Log(selectedEnemy);

        Enemy<Jackass> placedEnemy = new Enemy<Jackass> (listOfDerivedClasses[selectedEnemy].Name.ToString());
        placedEnemy.ScriptComponent.Initialize(
            speed_: speed,
            healthNotches_: healthNotches,
            healthpoints_: healthPoints,
            acceleration_: acceleration,
            rotation_: Quaternion.identity,
            position_: transform.position);
    }

}

I’m not super-familiar with the finer details of editor scripts, but there is this construct:

Unity - Scripting API: EditorGUI.BeginChangeCheck

It comes with a paired “End” call that allows you to check if there was changes to the data during that span, and only then do you call Dirty(). Take a look for examples on how to use the above API before you spend too much more time tinkering.

Also, there’s various tutorial series by this guy that are fantastically detailed:

2 Likes

You need to use SerializedObject update, and applyModifiedProperties.

2 Likes

With a little work, that did the trick, thanks!

2 Likes

I’ve done both of the Catlikecoding tutorials, this one deals with the SerializedObject:

2 Likes

Alright, so I’ve gone over and implemented the catlike coding inspectors a couple times, along with a few additional resources (thanks again for pointing me in the right direction!) but now I’m running into the same problem again and I can’t seem to solve it.

I’m working on expanding my custom inspector so that I can have enemies with more/less health than usual in certain situations and I’ve managed to accomplish this:

[CustomEditor(typeof(EnemyFactory))]
public class EnemyFactoryEditor : Editor
{
    int choiceIndex = 0;
    bool customToggle = false;

    float healthPoints;
    int healthNotches;
    float speed;
    float acceleration;

    string[] inspectorChoices = new string[0];
    List <System.Type> listOfDerivedClasses = Assembly.GetExecutingAssembly ().GetTypes ().Where (x => x.IsSubclassOf (typeof(EnemyBase))).ToList ();

    SerializedObject _editorObject;
    SerializedProperty _enemyInt;
    SerializedProperty _customBool;

    SerializedProperty _healthPoints;
    SerializedProperty _healthNotches;
    SerializedProperty _speed;
    SerializedProperty _acceleration;

    void OnEnable () {
        _editorObject = new SerializedObject (target);
        _enemyInt = _editorObject.FindProperty ("selectedEnemy");
        _customBool = _editorObject.FindProperty ("customEnemy");

        _healthPoints = _editorObject.FindProperty ("healthPoints");
        _healthNotches = _editorObject.FindProperty ("healthNotches");
        _speed = _editorObject.FindProperty ("speed");
        _acceleration = _editorObject.FindProperty ("acceleration");
    }

    public override void OnInspectorGUI () {
        _editorObject.Update ();
        //EnemyFactory targetFactory = (EnemyFactory)target;

        inspectorChoices = new string[listOfDerivedClasses.Count];

        for (int i = 0; i < listOfDerivedClasses.Count; i++) {
            inspectorChoices [i] = listOfDerivedClasses [i].Name.ToString ();
        }

        choiceIndex = EditorGUILayout.Popup("Enemy: ", _enemyInt.intValue, inspectorChoices);
        _enemyInt.intValue = choiceIndex;

        customToggle = EditorGUILayout.BeginToggleGroup ("Override defaults: ", customToggle);
            healthPoints = EditorGUILayout.FloatField ("Health points: ", healthPoints);
            healthNotches = EditorGUILayout.IntField ("Health notches: ", healthNotches);
            speed = EditorGUILayout.FloatField ("Speed: ", speed);
            acceleration = EditorGUILayout.FloatField ("Acceleration: ", acceleration);
        EditorGUILayout.EndToggleGroup();

        _customBool.boolValue = customToggle;

        _healthPoints.floatValue = healthPoints;
        _healthNotches.intValue = healthNotches;
        _speed.floatValue = speed;
        _acceleration.floatValue = acceleration;

        //DrawDefaultInspector();

        _editorObject.ApplyModifiedProperties();
    }
}

Basically, it allows me to specify whether or not I’m overriding the default values an enemy may have. It’s a little ugly, like most of my code, but it half works. Once again, I’m faced with it not saving the values (aside from the dropdown, which works flawlessly for some reason) when I take focus away from the object, press play, or do anything. What completely obvious thing have I missed here?

Bumping for the morning/afternoon crew

I think you need to add Begin/ EndChangeCheck calls and SetDirty

According to this, SetDirty is only supposed to be used if you’re not using SerializedProperty, but I’m using them for all my editor’s controls.

Ah, yeah… I guess I’m stumped then. :face_with_spiral_eyes:

It turns out it was just a stupid mistake I made while coding too late at night.

        customToggle = EditorGUILayout.BeginToggleGroup ("Override defaults", _customBool.boolValue);
            healthPoints = EditorGUILayout.FloatField ("Health points: ", _healthPoints.floatValue);
            healthNotches = EditorGUILayout.IntField ("Health notches: ", _healthNotches.intValue);
            speed = EditorGUILayout.FloatField ("Speed: ", _speed.floatValue);
            acceleration = EditorGUILayout.FloatField ("Acceleration: ", _acceleration.floatValue);
        EditorGUILayout.EndToggleGroup();

Everything works now that I’ve changed these lines to this.

1 Like