Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How to make copy of GameObject without breaking connection with prefab

Discussion in 'Editor & General Support' started by Skougi, Jun 11, 2019.

  1. Skougi

    Skougi

    Joined:
    Oct 11, 2018
    Posts:
    2
    There is an instantiated GameObject from the prefab in the scene, I tried to create a copy via GameObject.
    Instantiate, but in this case the prefab from which the original was created is not considered the prefab of the copy.

    Is there a way to copy GameObject without losing connection to the prefab?
    Ideally, it should work as a context command Duplicate

    fire_test - original GameObject
    fire_test(Clone) - copy via GameObject.Instantiate (with broken connection to prefab)
    fire_test (1) - copy via context menu command "Duplicate"


    My script fo copying GamObject
    Code (CSharp):
    1.     public class Copier : MonoBehaviour
    2.     {
    3.         public void MakeCopy()
    4.         {
    5.             Instantiate(gameObject);
    6.         }
    7.     }
    Code (CSharp):
    1.     [CustomEditor(typeof(Copier))]
    2.     public class CopierEditor : Editor
    3.     {
    4.         public override void OnInspectorGUI()
    5.         {
    6.             DrawDefaultInspector();
    7.  
    8.             var copier = (Copier) target;
    9.             if(copier == null) return;
    10.            
    11.             if (GUILayout.Button("Make copy"))
    12.             {
    13.                 copier.MakeCopy();
    14.             }
    15.         }
    16.     }
     
  2. Rotary-Heart

    Rotary-Heart

    Joined:
    Dec 18, 2012
    Posts:
    483
    It sounds like what you need is:

    Code (CSharp):
    1. PrefabUtility.InstantiatePrefab(gameObject);
    source
     
  3. Skougi

    Skougi

    Joined:
    Oct 11, 2018
    Posts:
    2
    PrefabUtility.InstantiatePrefab(gameObject); returns null.
    the reason I want to create a copy instead of re-instantiating the prefab is that the values in GameObject may differ from those in the prefab