Custom inspector field doesn't get set

I have the following custom inspector code:

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

[CustomEditor(typeof(Tower))]
public class TowerEditor : Editor
{
    public string Path;

    public override void OnInspectorGUI()
    {
        Tower Tower = target as Tower;

        EditorGUILayout.PrefixLabel("Path");
        Tower.Path = EditorGUILayout.TextArea(Tower.Path);

        this.DrawDefaultInspector();
    }
}

Tower.Path is a string. When I edit it, its all fine and I can switch to other objects and the field stays as it should when I switch back. When I click play the field gets reverted back to its old value.

Why does it revert back?

2 Answers

2

Your path is not getting serialized. This means that Path is either private, a property on Tower which will not work or the Path variable stored in your Tower object is not a [System.Serializable] type.

If Path is a property then make sure the property gets and sets a private field and make sure that private field has the [SerializeField] attribute.

[SerializeField]
string path = "";
public string Path
{
    get
    {
        return path;
    }
    set
    {
        path = value;
    }
}

To prevent the path value from ever appearing in the inspector you can also add the attribute [HideInInspector]. This will allow you to use the call DrawDefaultInspector() for all fields of your class not marked [HideInInspector] and allow you to only write code for the fields and properties you wish to have a custom inspector for.

If Path is stored as your own class then be sure to mark that class as [System.Serializable]

[System.Serializable]
public class MyClass
{
    public string path;
}

and again if any fields in that class are private they will also have to be marked [SerializeField].

Hope this helps.

I had the same in the link below is my forum post with the answer to my problem. Hope it also helps you.

1