Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Skjalg · Sep 20, 2011 at 08:28 AM · editorprefabcloneduplicate

How do I properly duplicate an object in a editor script?

Hi.

I am writing an editor script that lets you duplicate what you have selected around even easier than with ctrl+d.

But when I use the following code on a barrel I get "barrel(Clone)" as a result and the newly created object is not a prefab.

 GameObject go = Object.Instantiate(transform.gameObject, transform.position, transform.rotation) as GameObject;

What I am basically after is the exact code behind the ctrl+d functionality in the Unity editor.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by thylaxene · Mar 29, 2012 at 07:38 AM

Or if you really want recreate the way the Editor duplicates things try this (Unity 3.5).

 [MenuItem("Extra/Duplicate Selected")]
     public static void DuplicateSelected ()
     {
         Object prefabRoot = PrefabUtility.GetPrefabParent (Selection.activeGameObject);
         
         if (prefabRoot != null)
             PrefabUtility.InstantiatePrefab (prefabRoot);
         else
             Instantiate (Selection.activeGameObject);
     }
Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lokesh.sehgal · Nov 14, 2012 at 02:38 PM 0
Share

thylaxene: I tried this but got the following error: The type or namespace name `$$anonymous$$enuItem' could not be found

Please help me!

avatar image Ben Blaut · Nov 14, 2012 at 09:38 PM 1
Share

But how would you mimic ctrl + d on prefabs in the "Project" view?

avatar image Skjalg · Nov 15, 2012 at 10:03 AM 0
Share

lokesh: You need to have using UnityEditor at the top of your script.

Ben: I have no idea.

avatar image Ben Blaut · Nov 15, 2012 at 06:07 PM 2
Share

Figured it out...

 AssetDatabase.CopyAsset(oldPath, newPath);
 AssetDatabase.Refresh();
avatar image KillMobil · Jan 08, 2015 at 01:38 PM 1
Share

While this is correct its not 100% similar to the edit "Edit/Duplicate" If you try to duplicate something from with in the prefab it will find its root and duplicate that.

The Best thing is to invoke the edit window function with the code below:

 EditorWindow.focusedWindow.SendEvent (EditorGUIUtility.CommandEvent ("Duplicate"));

is also suggest you focus on the Sceneview first cause you could accidentally duplicate folder and scenes and then you will have something like this.

 SceneView.lastActiveSceneView.Focus ();
                 EditorWindow.focusedWindow.SendEvent (EditorGUIUtility.CommandEvent ("Duplicate"));

avatar image
2

Answer by Sbd · Sep 20, 2011 at 09:57 AM

This will do the same as pressing ctrl + d

 [MenuItem("Extra/Duplicate Selected Prefab")]
 public static void DuplicateSelectedPrefab()
 {
     Object prefabRoot = EditorUtility.GetPrefabParent(Selection.activeGameObject);
     EditorUtility.InstantiatePrefab(prefabRoot);
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Anisoropos · Mar 20, 2021 at 08:21 AM

Updating because GetPrefabParent has been deprecated around 2019.1 (plus some extra functionality)

This works on the scene view only - if you want to duplicate in the project (ie. assets) see Ben Blaut's comment

         // Map it to Alt + D
         [UnityEditor.MenuItem("GaneObject/Duplicate &D", false, 0)]
         public static void Duplicate()
         {
             List<UnityEngine.Object> clones = new List<UnityEngine.Object>();
 
             foreach (GameObject o in Selection.gameObjects)
             {
                 if (!o.transform) continue; // Scene view
                 GameObject clone;
 
                 GameObject prefab = PrefabUtility.GetCorrespondingObjectFromSource(o);
                 if (prefab != null)
                     clone = PrefabUtility.InstantiatePrefab(prefab, o.transform.parent) as GameObject;
                 else
                     clone = UnityEngine.Object.Instantiate(o, o.transform.parent);
 
                 if (clone == null) continue;
 
                 // Do any operations you want on to the cloned object (otherwise this function behaves just like Ctrl+D
                 // <---- CUSTOM LOGIC BEGIN ----> 
 
                 // ie. If you want to randomize scale / rotation you can do so here
                 // clone.transform.localScale = ;
                 // clone.transform.rotation = ;
 
                 // <---- CUSTOM LOGIC END ----> 
 
                 clones.Add(clone);
 
                 // Register the duplicated objects to be able to undo
                 Undo.RegisterCreatedObjectUndo(clone, "Duplicate");
             }
 
             if (clones.Count == 0) return;
 
             // Select the duplicated objects
             Selection.objects = clones.ToArray();
         }


Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ianny_dev · Jul 18, 2021 at 09:07 AM 0
Share

When I duplicated the gameobject that include prefabs - prefabs in newly instantiated copy becoms non-prefabs.

Is there a solution for to keep them as prefabs?

Thank you :)

avatar image huulong · May 10 at 03:27 PM 0
Share

Don't forget PrefabUtility.SetPropertyModifications(clone, PrefabUtility.GetPropertyModifications(o)); to copy modifications done on the copied prefab instance.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to reset a component on duplication? 4 Answers

Placing Prefabs in Prefabs. 9 Answers

FindGameObjectsWithTag returns extra prefabs nowhere in the hierarchy 0 Answers

Prefab referenced into Inspector and then Istantiated: Twice in memory? 0 Answers

OnTriggerEnter2D not working on sprite's prefab clones 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges