- Home /
Deep Copy ScriptableObject
I've been trying to clone a ScriptableObject with the following script:
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
But it is producing this error:
SerializationException: Type UnityEngine.ScriptableObject in assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable.
How can we perform a deep copy in this case?
Answer by slightchan · Dec 17, 2012 at 11:41 AM
I think this editor method may help you: EditorUtility.CopySerialized, I tried it, and it worked.
Answer by tomka · Jun 01, 2012 at 04:11 AM
Just a hunch, but does Object.Instantiate create a deep copy for your object?
Answer by Streamfall · Dec 08, 2015 at 08:36 PM
Just in case this is useful for others.
EditorUtility.CopySerialized does not work on iOS.
However, making your objects ScriptableObject then Instantiating the object does work.
How would you use an Editor script on iOS?! Of course that it won't work, it shouldn't work in any build, on iOS or not...
Your answer
![](https://koobas.hobune.stream/wayback/20220613072214im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
cloning of ScriptableObject 2 Answers
How do I clone a ScriptableObject reference at runtime? 1 Answer
MonoBehaviours with ScriptableObjects and duplicating` 1 Answer
Unique function for each instance of a scriptable object 2 Answers
How do you dynamically create serialized fields in the inspector? 1 Answer