在 Unity 中退出 Playmode 后返回 ScriptableObject 的原始值

Tie*_*ung 2 unity-game-engine scriptable-object

我有一个像这样的 ScriptableObject

在此输入图像描述

在 Playmode 期间我调整 CurrenHealthValue

在此输入图像描述

当我存在 Playmode 时,CurrentHealthValue=80 不会返回到 40,我知道这是 ScriptableObject 的工作原理,但我想知道是否有任何方法可以在存在 Playmode 后自动返回 40 原始值,而不是手动返回在开始新的 Playmode 之前将值重写为 40。

Mil*_*bec 6

在这种情况下,我使用将EditorJsonUtility初始对象的副本保存为 JSON,然后在完成后覆盖目标对象。

在这种情况下,代码看起来类似于:

using UnityEngine;
#if UNITY_EDITOR // makes intent clear.
using UnityEditor;
#endif

[CreateAssetMenu ( fileName = "TestScriptableObject", menuName = "TestScriptableObject", order = 1 )]
public class TestScriptableObject : ScriptableObject
{
    public int Field1;
    public float Field2;
    public Vector2 Field3;

#if UNITY_EDITOR
    [SerializeField] private bool _revert;
    private string _initialJson = string.Empty;
#endif

    private void OnEnable ( )
    {
#if UNITY_EDITOR
        EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
        EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
#endif
    }

#if UNITY_EDITOR
    private void OnPlayModeStateChanged ( PlayModeStateChange obj )
    {
        switch ( obj )
        {
            case PlayModeStateChange.EnteredPlayMode:
                _initialJson = EditorJsonUtility.ToJson ( this );
                break;

            case PlayModeStateChange.ExitingPlayMode:
                EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
                if ( _revert )
                    EditorJsonUtility.FromJsonOverwrite ( _initialJson, this );
                break;
        }
    }
#endif
}
Run Code Online (Sandbox Code Playgroud)