Last active
September 18, 2024 06:22
-
-
Save yCatDev/d54c6c4d757adb5df38b3e53e4d0f954 to your computer and use it in GitHub Desktop.
Simple editor workaround for ScriptableObjects that fix saving changes after play mode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if UNITY_EDITOR | |
using System.Collections.Generic; | |
using ClickerFramework.Abstract; | |
using UnityEngine; | |
using UnityEditor; | |
[InitializeOnLoad] | |
public static class ScriptableObjectProtector | |
{ | |
private static bool _playing = false; | |
static ScriptableObjectProtector() | |
{ | |
EditorApplication.update += OnUpdate; | |
} | |
private static void OnUpdate() | |
{ | |
if (EditorApplication.isPlayingOrWillChangePlaymode && !_playing) | |
{ | |
foreach (var scriptableObject in FindScriptableObjectsByType()) | |
{ | |
EditorUtility.SetDirty(scriptableObject); | |
Undo.RegisterCompleteObjectUndo(scriptableObject, scriptableObject.name); | |
} | |
_playing = true; | |
} | |
if (!EditorApplication.isPlayingOrWillChangePlaymode && _playing) | |
{ | |
//Debug.Log("Revering ScriptableObjects"); | |
_playing = false; | |
Undo.PerformUndo(); | |
} | |
} | |
private static List<ScriptableObject> FindScriptableObjectsByType() | |
{ | |
var assets = new List<ScriptableObject>(); | |
var guids = AssetDatabase.FindAssets($"t:{typeof(ScriptableObject)}"); | |
foreach (var t in guids) | |
{ | |
var assetPath = AssetDatabase.GUIDToAssetPath(t); | |
var asset = AssetDatabase.LoadAssetAtPath<ScriptableObject>(assetPath); | |
if (asset != null) | |
{ | |
assets.Add(asset); | |
} | |
} | |
return assets; | |
} | |
} | |
#endif |
It looks like this relies on not performing any undo-able action in the Editor during Play mode, since that action would be undone instead. This includes things like selecting something in the project or hierarchy. I wish there was a way to undo a specific action. Still this was very insightful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After experimenting for a while, ScriptableObject actually won't get saved in editor even whole project is saved unless your call SetDirty explicitly on the object. Although the asset inspector shows the change made in play mode, the object won't be saved util you edit the value in inspector. In other words, don't bother to undo the changes from play mode. It's fine to leave it there and your data is intact in asset file.