Skip to content

Instantly share code, notes, and snippets.

@yCatDev
Last active September 18, 2024 06:22
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
@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