hello. i’m new to unity and programming in general, so let me start by apologizing for the noobish question… here goes.
i have been playing with custom asset derived from scriptable objects (following Jacob Pennock’s excellent guide http://www.jacobpennock.com/Blog/?p=670). i have successfully setup creep attributes and global configuration using that. my question is why scriptable object derived asset is not used for saving game state?
i have done some research on saving games, and there are discussions on doing that through xml serialization and mono serialization etc, but i haven’t been able to find any information on saving game using scriptable object derived asset. i feel that there must be a fundamental reason why no one else is doing it, but i just cannot figure out what that reason is. i would appreciate if someone could shed some light on that. thanks!
I wondered the same thing, so I conducted some test to find out.
The reason is (and I could be wrong about this), any runtime changes to a ScriptableObjects (SO) are not saved on play exit. When you use a SO in game, what really happens is a new instance of the object is instantiated, and that instance is used. The base .asset file is not affected.
Now, when in editor mode things can be a little deceiving. Depending on how your variables are setup in your SO, if you make a change to some variable in you SO while in play mode, and then exit play mode, if you then inspect your .asset file, you’ll see that the variable is set to whatever you set it to in play mode.
This isn’t an illusion. The variable has indeed changed. However, in order for that change to be permanent, you need to call Editor.SetDirty(target_script_which_references_SO); I think you can use the SO itself as a parameter too, but I’m not positive.
If you don’t call that, and exit/reopen Unity, you’ll see that the variable in your SO reset to its last saved value, which will not be the value you set in play mode. Since it’s impossible to call an editor function (SetDirty) from within a game, this means it’s impossible to save runtime changes to a SO.
With that said, I think it could eventually be possible. Unity obviously already has a method for creating Objects which can be changed permanently during runtime (TerrainData and Texture2D). I believe it does this by using the .asset files directly rather than creating an instance of object.
The Unity people just need to give us a way to mark our SO’s as persistent, so they can be edited at runtime and have all changes made permanent.