What happens when i Copy an object (From Programming point of view)


Pure curiosity… I wonder, what actually happens, when i go to Edit > Copy, while selecting a gameObject (In the Hierarchy), under the hood?

I see that all of the referencing, that the Components of the copied object are kept, even if i delete it and then paste it in the scene…

•Does Unity creates something like a virtual instance of that object?

• Does Unity goes through all of the properties of all components and records their state, at the moment of copy?

1: Can i replicate the copy via C# in unity (Without doing any DLL stuff)?

I was wondering if i can do it for many objects, for example i have a button and select object (One by one, NOT all, at the same time) and add them to (so to speak) copy List… So i can choose, which one to paste afterwards…

Thanks :slight_smile:

Well, we can’t tell how the editor actually performs a copy and paste action, however it most likely (99%) uses Unity’s serialization system to serialize the selected objects when you copy them and deserialize them when pasting. At least the ISerializationCallbackReceiver callbacks are called whenever you copy / paste objects in the hierarchy.

I’m not sure what you actually want to do. Unity’s serialization system only works inside the editor. You can’t save things at runtime. If you want to copy multiple objects in the editor you can simply hold the CTRL key and select as many objects as you want. When you press CTRL+C you will copy all objects you have selected.

If you want to automate things inside the Unity editor you can use the Selection class in an editor script to select any object inside the editor. With EditorApplication.ExecuteMenuItem you can trigger “Edit/Copy” and “Edit/Paste”.

If you want such functionality at runtime you have to do everything yourself. At runtime Unity’s serialization system is not available.

As i said in the beginning it’s not clear what and where / when you want copy “something”. If my answer isn’t enough you should edit your question and be more clear about what you want to do.