Cloning a GameObject with Linked Prefab Children


Say we have three objects: A Prefab Asset (call it “A”), a regular GameObject in the scene (“B”), and a prefab instance of A that is a child of B (“C”):

Prefab Asset A

Scene Hierarchy
GameObject B

  • Prefab Instance C (connected to Prefab Asset A)

I would like to clone GameObject B, in such a way that its children (i.e. Prefab Instance C) maintain their connections to their prefab assets, as well as any overrides they may have. This is trivial in the editor (using Duplicate, or Copy & Paste), however I need to do this via scripting.

UnityEditor.PrefabUtility.InstantiatePrefab doesn’t work, since it won’t accept a non-asset as a parameter, so I can’t pass it GameObject B. Object.Instantiate obviously won’t work either since it breaks the prefab connections. I’ve looked through the rest of PrefabUtility’s static methods and don’t see anything else there that’d be helpful, but I’m hoping that I’m missing something. Does anyone know of a way to do this via scripting?

Much thanks in advance.

(Unity 2019.4)

Use some tricks like UnityEditor.Unsupported.DuplicateGameObjectsUsingPasteboard?

UnityEngine.Object recordSelected = UnityEditor.Selection.activeObject;
UnityEditor.Selection.activeObject = GameObjectB;
UnityEditor.Selection.activeObject = recordSelected;