Tie*_*ung 2 unity-game-engine scriptable-object
我有一个像这样的 ScriptableObject
在 Playmode 期间我调整 CurrenHealthValue
当我存在 Playmode 时,CurrentHealthValue=80 不会返回到 40,我知道这是 ScriptableObject 的工作原理,但我想知道是否有任何方法可以在存在 Playmode 后自动返回 40 原始值,而不是手动返回在开始新的 Playmode 之前将值重写为 40。
在这种情况下,我使用将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)