- Home /
How to Serialize Scriptable Object at Runtime?
I know how to save them into .asset file in Editor, but how do I do this in the actual build?
BinaryFormatter is not happy about ScriptableObject...
I got this error in my build when I tried to serialize that at runtime:
SerializationException: Type UnityEngine.ScriptableObject in assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable.
Any thought on this?
Answer by Loius · May 18, 2014 at 05:54 AM
UnitySerializer is worth looking into. I don't know off the top of my head if it handles serializableObjects specifically, but it does normal unity-objects so it may be capable.
Otherwise you'll probably have to look into using Reflection. Essentially you'd have something like this:
foreach(var field in targetObject.GetFields()) {
SerializeSomehow(field.name, field.value);
}
You can check to be sure field.value is serializable before messing with it using some reflection stuff as well.
This STILL isn't going to be good enough if you need to serialize Vector3 or other non-serializable Unity structs. If it turns out you need some things like that included in your copied object, I'm at a loss. I have some scripts that literally just copy a certain type of SerializedObject into a copy specifically because I couldn't figure out how to handle those types. :(
Edit: But if you just need to copy from one scripto to another it would look like this:
public void CopyScriptable(ScriptableObject source, ScriptableObject target) {
if ( typeof(source) != typeof(target) ) {
// error message
return;
}
foreach(var field in source.GetType().GetFields()) {
field.SetValue(target, field.Getvalue(source));
}
}
Your answer
Follow this Question
Related Questions
Handle modified variables being temporarily reset at runtime 1 Answer
How to assign a class ID at runtime? 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Scriptableobject not saving if i force close the application. 1 Answer
Serializing specialized subclasses of generic classes not working 1 Answer