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?

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. :frowning:

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));
  }
}