unity-game-enginescriptable-object

Return a ScriptableObject's original value after quit Playmode in Unity


I have a ScriptableObject like this

enter image description here

and during Playmode I adjust the CurrenHealthValue

enter image description here

and when I exist the Playmode the CurrentHealthValue=80 doesn't return to 40, I know it was how ScriptableObject works but I want to know if there is any way which I can automatically return the 40 original value after exist the Playmode instead of manually rewrite the value to 40 before start the new Playmode.


Solution

  • In situations like this, I've used the EditorJsonUtility to save a copy of the initial object as JSON, and then overwritten the target object once I've finished.

    In this case, the code would look something similar to:

    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
    }