在编辑器会话之间存储编辑器值

时间:2019-06-14 08:29:23

标签: c# unity3d

我有以下创建自定义检查器窗口的EditorWindow脚本。在此窗口中按下按钮后,id将增加1。

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);
}

这很好用,但是当我启动播放模式或关闭统一编辑器时,id的增量值将丢失,并将被重置回10000。

使用int id的非静态版本将使该值在“播放”会话中保持不变,但在您合一后仍将丢失。

是否有一种方法可以在编辑器/社区会话之间存储此值,就像playerprefs一样,但是对于编辑器而言呢?

1 个答案:

答案 0 :(得分:4)

ScriptableObject

也许更像“统一”的方式是使用专用的ScriptableObject(另请参见Introduction to ScriptableObjects

您可以将其与[InitializeOnLoadMethod]结合使用,以实现一种加载方法,该方法将在优化编辑器后重新编译以创建ScriptableObject 一次后调用。

// 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;
}

确保将其放在单独的脚本中。

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();
    }
}

的巨大优势:

  • 与使用FileIO进行写入和保存相比,这是一种更快/更高效的方式,因为Unity会自动处理该ScriptableObject的(反序列化)。
  • 您不需要“手动”加载和保存数据..由于ScriptableObject的行为与任何其他预制件一样,它是自动完成的。
  • 您只需在资产中单击ScriptableObject实例即可直接更改值!

使用简单的文本文件

一个简单但效率不高的替代解决方案是将其存储到文件中,例如像这样的JSON

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();
        }
    }
}

当前,这在每次打开窗口时读取文件,并在每次单击按钮时写入文件。仍然可以改善。

同样,您可以使用[InitializeOnLoadMethod]来只读取一次文件-即当您打开编辑器或像这样重新编译时

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);
    }

    ...
}

为了优化保存并仅在保存到UnityEditor中时执行文件写入,您可以实施专用的AssetModificationProcessor,例如

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;
    }
}