Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Duplicate prefab instance via C#

Discussion in 'Prefabs' started by joshcamas, May 1, 2024.

  1. joshcamas

    joshcamas

    Joined:
    Jun 16, 2017
    Posts:
    1,279
    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...
     
  2. MirceaI

    MirceaI

    Unity Technologies

    Joined:
    Nov 24, 2020
    Posts:
    40
    Hello! Unfortunately we don't have public API for this, but we have one "Unsupported" function which does exactly what you need.

    Code (CSharp):
    1. using UnityEditor;
    2. using UnityEngine;
    3.  
    4. public class Clone : MonoBehaviour
    5. {
    6.     [MenuItem("MyMenu/CloneSelectedObjects")]
    7.     static void CloneSelectedObjects()
    8.     {
    9.         Unsupported.DuplicateGameObjectsUsingPasteboard();
    10.     }
    11. }
    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.
     
  3. unity_8A8EB2FD9F3BAB87D0FB

    unity_8A8EB2FD9F3BAB87D0FB

    Unity Technologies

    Joined:
    Aug 8, 2023
    Posts:
    2