Duplicate prefab instance via C#

I’m trying to duplicate a prefab instance in editor, identically to Ctrl-D.
I am using Unity 2020.3.42

This is my code:

var copy = UnityEditor.PrefabUtility.InstantiatePrefab(prefab, gameObject.transform.parent) as GameObject;
UnityEditor.PrefabUtility.SetPropertyModifications(copy, UnityEditor.PrefabUtility.GetPropertyModifications(gameObject));

The issue is that this seems not not correctly apply changes related to new components added to the prefab instance but not included in the original prefab itself.

Does anyone know how to solve this issue? This almost seems like a bug or oversight to me…

Hello! Unfortunately we don’t have public API for this, but we have one “Unsupported” function which does exactly what you need.

using UnityEditor;
using UnityEngine;

public class Clone : MonoBehaviour
{
    [MenuItem("MyMenu/CloneSelectedObjects")]
    static void CloneSelectedObjects()
    {
        Unsupported.DuplicateGameObjectsUsingPasteboard();
    }
}

This function is in the “Unsupported” namespace which means we reserve the right change or remove this function. This function also uses the current selection which means you need to set Selection.objects to the objects you want to clone.

There is some more discussion on [SOLVED] Duplicate Prefab Issue - Unity Forum