CopySerialized(Object, Object)
Copies all serialized properties of a Unity Object from one object to another.
Read time 2 minutesLast updated 5 days ago
Definition
- Type: Method
- Namespace: UnityEditor
- Assembly: UnityEditor.CoreModule
public static void CopySerialized(Object source, Object dest)
Parameters
Remarks
This method copies all serialized properties from the object to the object, overwriting values that are currently in the properties of . The fields that are included follow the script-serialization-rules.
sourcedestdestThis method is mostly useful when working with objects in assets. It is similar to Object.Instantiate in that it also copies the serialized properties of an object, but it overwrites an existing object, unlike which always creates a new object.
InstantiateNote that Object.hideFlags are not copied.
If the object being copied derives from MonoBehaviour or ScriptableObject, then must either be the same type as , or a base class of it. Otherwise, the types of and must be equal.
destsourcedestsourceBecause the Unity serializer is used to copy the values, if the ISerializationCallbackReceiver.OnBeforeSerialize method is implemented then it's invoked on the object before copying. If the ISerializationCallbackReceiver.OnAfterDeserialize method is implemented, it's invoked on the object after copying.
sourcedestThe following example shows how this method could be used to reset the properties of an object to match a 'reference' object, instead of manually resetting the properties to hardcoded values.
Examples
using System.Collections.Generic;using UnityEditor;using UnityEngine;[CreateAssetMenu]public class CopySerializedExample : ScriptableObject{ // Declare some serialized fields public int intValue; public string stringValue; public List<bool> listOfBools; #if UNITY_EDITOR [ContextMenu("Reset to reference")] public void ResetToReference() { // CopySerialized will overwrite the object name as well; we don't want that // so save it to a temporary variable so we can restore it afterwards var originalName = this.name; var reference = AssetDatabase.LoadAssetAtPath<CopySerializedExample>("Assets/ReferenceAsset.asset"); EditorUtility.CopySerialized(reference, this); // Restore the original name this.name = originalName; } #endif}