Skip to content

Instantly share code, notes, and snippets.

@yCatDev
Last active September 13, 2023 07:59
Show Gist options
  • Save yCatDev/d54c6c4d757adb5df38b3e53e4d0f954 to your computer and use it in GitHub Desktop.
Save yCatDev/d54c6c4d757adb5df38b3e53e4d0f954 to your computer and use it in GitHub Desktop.
Simple editor workaround for ScriptableObjects that fix saving changes after play mode.
#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
@abcjjy
Copy link

abcjjy commented Jan 7, 2022

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.

@Vanlalhriata
Copy link

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