- Home /
Persistence of ScriptableObjects between Scenes?
I've recently been looking at scriptable objects as a new tool to build my game, and I've recreated a set of classes that can hold variables and references for different data types that can be dropped into and shared between objects in my scene as required. Now, I'm aware that if I alter a scriptable object at runtime whilst I run it in the editor, it will actually save into the .asset file, meaning that it would also persist across scenes. I'm also aware that it will not do this at runtime in the build as it cannot serialise the data back into the .asset file outside of the editor. My question is, if I reference the .asset file in 2 different scenes and change it in one scene, will it keep the value when I load the other scene (i.e. will it keep the value in memory for the duration of the session within the build, or will it reload it from the .asset file when I switch scenes)?
Answer by Elango · Jul 18, 2020 at 05:21 AM
Changed values will stay for a whole application runtime as long as you not null all references in current scene and unload SO with
Resources.UnloadUnusedAssets();
or
Resources.UnloadAsset(so);
Thanks for your response on this! Just a couple more questions in regards to the answer you've given. Firstly, am I correct that SOs may not persist if I were to load an intermediate scene that doesn't have any references to them? Secondly, does Unity call Resources.UnloadUnusedAssets() itself at any point (I'm guessing it may call it once a scene has been loaded to clean up any objects that are hanging around, which leads me to the assumption in the former question)?
Loading new scene (not additive) will unload unused resources. So if there's no direct reference to SO in new scene (in inspector) it will be unloaded (assigning it in Awake/Start doesn't count as direct). If you store reference in static class variable it will stay. As far as i know Resources.UnloadUnusedAssets() called on enter playmode, loading scene (inc opening new scene in editor) and when memory limit reached.
Answer by RedHillbilly · Jul 29, 2021 at 06:00 PM
Answering here because it's the first hit on google. Found the solution to not unload scriptable objects between scenes, even if they are not referenced in one scene (http://answers.unity.com/comments/1569389/view.html ). Add the following snippet of code to you SO:
private void OnEnable() => hideFlags = HideFlags.DontUnloadUnusedAsset;
Your answer
Follow this Question
Related Questions
Understanding ScriptableSingleton 0 Answers
How to set the position of an object in another scene? 1 Answer
How do I use a game object to store a singleton? 1 Answer
Big problem with a small singleton 1 Answer
Timer Data Across Scene Changes 1 Answer