Dictionary becomes null unexpectedly when using a custom inspector

So I’ve been playing around with inspector scripts for the first time and I’m getting an unusual problem that I assume is related somehow to the way that inspector scripts behave:

[CustomEditor(typeof(TextureSaver))]
public class TextureSaver : Editor
{
    private Dictionary<string, string> matPathToTexPath;

// Use this for initialization
    void Start()
    {
        matPathToTexPath = new Dictionary<string, string>();
    }

    void BuildTextureDatabase()
    {
        if (matPathToTexPath == null)
        {
            Debug.Log("Problem!");
        }
    }

    public override void OnInspectorGUI()
    {
        if (GUILayout.Button("Save Textures"))
        {
            BuildTextureDatabase();
        }
    }

}

The problem is that if I go into play mode and then hit the “Save Textures” button, it prints “Problem” telling me that the dictionary is somehow null. How is this possible when I clearly set it in Start()?

If I create an Update() function and I use a keydown event to trigger BuildTextureDatabase(), then the dictionary is initialized properly. This leads me to believe that the problem is related to the way that editor scripts work.

So my guess is that Start() is not called because it’s not derived from MonoBehaviour but Editor, it seems Editor does not have a Start() or Update().

You will have to initialize it immediately or use lazy if prefered.

private Dictionary<string, string> matPathToTexPath = new Dictionary<string, string>();

or lazy:

 private Dictionary<string, string> _matPathToTexPath;
 private Dictionary<string, string> matPathToTexPath
 {
     get { return _matPathToTexPath ?? (_matPathToTexPath = new Dictionary<string, string>()); }
 }

It’s null because you have no values in your dictionary…
And if you want values as Texture you should use Dictionary

make sure you add line : using System.Collections.Generic; in first line