简体   繁体   中英

Store editor values between editor sessions

I have the following EditorWindow script that creates a custom inspector window. Upon pressing the button in this window the id will be incremented by one.

static int id = 10000;

[MenuItem("Custom/CustomMenu")]
static void Init()
{
    // Get existing open window or if none, make a new one:
    CustomMenu window = (CustomMenu)EditorWindow.GetWindow(typeof(CustomMenu));
    window.Show();
}

if (GUILayout.Button("someButton"))
{
    id++;
    Repaint();
    EditorUtility.SetDirty(this);
}

This works fine, however when I launch play mode, or close the unity editor the incremented value of id is lost, and will be reset back to 10000.

Using a non static version of int id will make the value persist through "play" sessions, but will still be lost once you close unity.

Is there a way to store this value between editor/unity sessions, something like a playerprefs but for the editor maybe?

ScriptableObject

Maybe more like the "Unity" way to go would be to use a dedicated ScriptableObject (also see the Introduction to ScriptableObjects )

You could combine it with an [InitializeOnLoadMethod] in order to implement a loading method that will be called after opnening the editor and after re-compile to create the ScriptableObject once .

// we don't need the CreateAssetMenu attribute since the editor window
// will create the ScriptableObject once by itself
public class CustomMenuData : ScriptableObject
{
    public int Id;
}

Make sure to place it in a separate script.

public class CustomMenu : EditorWindow
{
    // we can go privtae again ;)
    private static CustomMenuData data;

    // This method will be called on load or recompile
    [InitializeOnLoadMethod]
    private static void OnLoad()
    {
        // if no data exists yet create and reference a new instance
        if (!data)
        {
            // as first option check if maybe there is an instance already
            // and only the reference got lost
            // won't work ofcourse if you moved it elsewhere ...
            data = AssetDatabase.LoadAssetAtPath<CustomMenuData>("Assets/CustomMenuData.asset");

            // if that was successful we are done
            if(data) return;

            // otherwise create and reference a new instance
            data = CreateInstance<CustomMenuData>();

            AssetDatabase.CreateAsset(data, "Assets/CustomMenuData.asset");
            AssetDatabase.Refresh();
        }
    }

    [MenuItem("Custom/CustomMenu")]
    private static void Init()
    {
        // Get existing open window or if none, make a new one:
        var window = (CustomMenu)EditorWindow.GetWindow(typeof(CustomMenu));

        window.Show();
    }

    private void OnGUI()
    {
        // Note that going through the SerializedObject
        // and SerilaizedProperties is the better way of doing this!
        // 
        // Not only will Unity automatically handle the set dirty and saving
        // but it also automatically adds Undo/Redo functionality!
        var serializedObject = new SerializedObject(data);

        // fetches the values of the real instance into the serialized one
        serializedObject.Update();

        // get the Id field
        var id = serializedObject.FindProperty("Id");

        // Use PropertyField as much as possible
        // this automaticaly uses the correct layout depending on the type
        // and automatically reads and stores the according value type
        EditorGUILayout.PropertyField(id);

        if (GUILayout.Button("someButton"))
        {
            // Only change the value throgh the serializedProperty
            // unity marks it as dirty automatically
            // also no Repaint required - it will be done .. guess .. automatically ;)
            id.intValue += 1;
        }

        // finally write back all modified values into the real instance
        serializedObject.ApplyModifiedProperties();
    }
}

The huge advantage of this:

  • It is way faster/more efficient then using FileIO for writing and saving since Unity automatically takes care of the (de)serialization of that ScriptableObject.
  • You don't need to "manually" load and save the data .. it is done automatically since the ScriptableObject behaves like any other prefab.
  • You can simply click on the ScriptableObject instance within your Assets and directly change the values!

Using a simple text File

A simple but not that efficient alternative solution would be to store it into a file eg as JSON like this

using System.IO;
using UnityEditor;
using UnityEngine;

public class CustomMenu : EditorWindow
{
    private const string FileName = "Example.txt";

    // shorthand property for getting the filepath
     public static string FilePath
     {
         get { return Path.Combine(Application.streamingAssetsPath, FileName); }
     }

    private static int id = 10000;

    // Serialized backing field for storing the value
    [SerializeField] private int _id;

    [MenuItem("Custom/CustomMenu")]
    static void Init()
    {
        // Get existing open window or if none, make a new one:
        CustomMenu window = (CustomMenu)EditorWindow.GetWindow(typeof(CustomMenu));

        if (File.Exists(FilePath))
        {
            // read the file content
            var json = File.ReadAllText(FilePath)

            // If the file exists deserialize the JSON and read in the values
            // for only one value ofcourse this is overkill but for multiple values
            // this is easier then parsing it "manually"
            JsonUtility.FromJsonOverwrite(json, window);

            // pass the values on into the static field(s)
            id = window._id;
        }

        window.Show();
    }

    private void OnGUI()
    {
        id = EditorGUILayout.IntField(id);

        if (GUILayout.Button("someButton"))
        {
            id++;
            Repaint();
            EditorUtility.SetDirty(this);

            // do everything in oposide order
            // first fetch the static value(s) into the serialized field(s)
            _id = id;

            // if not exists yet create the StreamingAssets folder
            if (!Directory.Exists(Application.streamingAssetsPath))
            {
                AssetDatabase.CreateFolder("Assets", "StreamingAssets");
            }

            // serialize the values into json
            var json = JsonUtility.ToJson(this);

            // write into the file
            File.WriteAllText(FilePath, json);

            // reload the assets so the created file becomes visible
            AssetDatabase.Refresh();
        }
    }
}

Currently this reads the file everytime you open the window and writes it everytime you click the button. This can stil be improved.

Again you could use [InitializeOnLoadMethod] in order to read the file only once - namely when you open the editor or recompile like

public class CustomMenu : EditorWindow
{
    // Instead of having the field values directly as static fields
    // rather store the information in a proper serializable class
    [Serializable]
    private class CustomMenuData
    {
        public int Id;
    }

    // made this publlic for the saving process (see below)
    public static readonly CustomMenuData data = new CustomMenuData();

    // InitializeOnLoadMethod makes this method being called everytime
    // you load the project in the editor or after re-compilation
    [InitializeOnLoadMethod]
    private static void OnLoad()
    {
        if (!File.Exists(FilePath)) return;

        // read in the data from the json file
        JsonUtility.FromJsonOverwrite(File.ReadAllText(FilePath), data);
    }

    ...
}

In order to optimize the saving and perform the filewrite only when you save in the UnityEditor you could implement a dedicated AssetModificationProcessor like

public class CustomMenuSaver : SaveAssetsProcessor
{
    static string[] OnWillSaveAssets(string[] paths)
    {
        // do change nothing in the paths
        // but additionally store the data in the file

        // if not exists yet create the StreamingAssets folder
        if (!Directory.Exists(Application.streamingAssetsPath))
        {
            AssetDatabase.CreateFolder("Assets", "StreamingAssets");
        }

        // serialize the values into json        v That's why I made it public
        var json = JsonUtility.ToJson(CustomMenu.data);

        // write into the file         v needs to be public as well
        File.WriteAllText(CustomMenu.FilePath, json);            

        return paths;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM