Skip to content

Instantly share code, notes, and snippets.

@shadesbelow
Created May 11, 2023 14:09
Show Gist options
  • Save shadesbelow/7b448c48cdfae36e747f5f839d645c40 to your computer and use it in GitHub Desktop.
Save shadesbelow/7b448c48cdfae36e747f5f839d645c40 to your computer and use it in GitHub Desktop.
A base class to make a Scriptable Object reset its values after exiting play mode
Using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class ResettableScriptableObject : 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment