Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 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
3
Question by LW · Nov 20, 2016 at 08:22 PM · editor-scriptingeventduplicate

Unity Duplicate Event

Hi Everyone,

I could use some help getting the Duplicate event in editor.

I've tried catching 'Paste' and 'Duplicate' but they do not get called when I look for them.

Additionally, I've tried to put an event handler in the EditorApplication.hierarchyWindowItemOnGUI to see if the commands are caught inside that but those commands do not appear.

Catching duplicate events in Unity is one of the single most frustrating things I've dealt with in Unity. It feels like handling this was an afterthought...

Any help is appreciated.

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

5 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Adam-Mechtley · Nov 20, 2016 at 09:00 PM

Hi @LW! Can you provide some more information? The following example works for me:

 using UnityEditor;
 using UnityEngine;
 
 [InitializeOnLoad]
 public class Test {
 
     static Test () {
         EditorApplication.hierarchyWindowItemOnGUI += delegate(int instanceID, Rect selectionRect)
         {
             if (Event.current.commandName == "Duplicate")
             {
                 Debug.Log ("Duplicated");
             }
         };
     }
 }
 
Comment
Add comment · Show 11 · 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 LW · Nov 21, 2016 at 10:38 PM 0
Share
 protected static void OnHierarchyWindowItemOnGUI(int n, Rect rt)
         {
             Debug.Log("OnHierarchyWindowItemOnGUI()");
             if ("Duplicate" == Event.current.commandName)
             {
                 Debug.Log("Copy was made... " + UnityEditor.Selection.activeGameObject);
             }
         }

Prints out: OnHierarchyWindowItemOnGUI() but then nothing. So, still no duplicate getting invoked. Running 5.4.1f1 Personal

avatar image LW · Nov 21, 2016 at 10:47 PM 0
Share

In fact, Event.current.commandName is an empty string.

avatar image Adam-Mechtley · Nov 22, 2016 at 07:05 AM 0
Share

Where does this method exist and how is it being registered?

avatar image LW · Nov 22, 2016 at 12:07 PM 0
Share

I tried this function in a $$anonymous$$onoBehaviour that is attached to the object being duplicated as well as a custom EditorWindow.

avatar image Adam-Mechtley LW · Nov 22, 2016 at 09:22 PM 0
Share

Can you provide some example code where you define this method and register it as an event handler? Can you verify that the script is in an Editor compilation pass (i.e. in an Editor folder)?

avatar image LW Adam-Mechtley · Nov 22, 2016 at 09:53 PM 0
Share

Sure thing! I'm at a loss....

The class is located in a folder entitled, 'editor' (the 'e' is not capitalized).

         [InitializeOnLoad]
         public class ExampleEditorWindow : EditorWindow
         {
             static ExampleEditorWindow()
             {
                 Debug.Log("static ExampleEditorWindow::ctor()");
                 EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
             }
 
             protected static void OnHierarchyWindowItemOnGUI(int n, Rect rt)
             {
                 string sz = Event.current.commandName;
                 switch (sz)
                 {
                     case null: Debug.Log("commandName is null"); break;
                     case "": Debug.Log("commandName is empty; instanceId is " + n + " which is " + EditorUtility.InstanceIDToObject(n)); break;
                     default: Debug.Log("Command name: " + sz); break;
                 }
 
                 if ("Duplicate" == Event.current.commandName)
                 {
                     Debug.Log("Copy was made... " + Selection.activeGameObject);
                 }
             }
         }
 

Thanks for the help on this!

Output:

The instance id 'n' and the name of every GameObject in the hierarchy... and something that doesn't have a name, only an instance id.

Show more comments
avatar image Bunny83 · Nov 22, 2016 at 10:57 PM 1
Share

Interesting topic ^^. I just had a look myself. I used this script:

 using UnityEditor;
 using UnityEngine;
 
 [InitializeOnLoad]
 public class Test
 {
     static Test
     {
         EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemGUI;
     }
     static void OnHierarchyWindowItemGUI(int instanceID, Rect selectionRect)
     {
         // ignore items which are not selected
         if (Selection.activeInstanceID != instanceID)
             return;
 
         Event e = Event.current;
         if (e.type == EventType.ValidateCommand || e.type == EventType.ExecuteCommand)
         {
             var o = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
             if (o != null)
                 Debug.Log("Event: " + e.type + " command: " + e.commandName + " item: " + o.name);
         }
     }
 }

Here are my results:

  • executing copy / paste / rename doesn't cause any command to be executed.

  • only "duplicate" and "delete" are catched.

  • The commands are only send when you either press CTRL+D / del or by using the corresponding command from the Edit menu

  • Note: strangely the commands are not sent when you use the context menu.

I'm currently using Unity 5.3.6f1 on Windows10 x64. $$anonymous$$aybe it depends on your operating system. I guess the behaviour is different on $$anonymous$$ac or Linux.

avatar image Adam-Mechtley Bunny83 · Nov 22, 2016 at 11:08 PM 0
Share

@Bunny83 Would you $$anonymous$$d submitting a bug report on this, please?

Show more comments
avatar image
2

Answer by Glurth · Nov 25, 2016 at 05:37 PM

Facing the same issue, and not really liking any of the other answers, particularly since the context menu does not work with them. Here is a simple workaround I came up with. I've only tested to confirm it detects duplicates, there my be other things that cause a detection I'm not aware of yet.

 [ExecuteInEditMode] 
 public class DuplicatableObject : MonoBehaviour {
 
     public int instanceID=0; //this value is duplicated with the gameobject
     void Awake()
     {
         if (instanceID != 0)
         {
             Debug.Log("Duplication Detected of " + gameObject.name + " oldID:" + instanceID + " newID: " + gameObject.GetInstanceID());
         }
         instanceID =gameObject.GetInstanceID();
     }
 
 }


Comment
Add comment · Show 8 · 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 LW · Nov 25, 2016 at 05:41 PM 0
Share

@Glurth ha ha nice, man! Unfortunately, it won't allow me to catch the duplicate in editor unless I execute in edit mode, though, right? I supposed it would be possible to check the value in an editor script and if so then handle my duplication rules... Thank you, @Glurth!

avatar image Glurth LW · Nov 25, 2016 at 05:49 PM 0
Share

[ExecuteInEdit$$anonymous$$ode] I just put that at the top, and it worked fine in the editor, without hitting play. (ans updated) Or perhaps I misunderstand, is that option not possible in your situation?

avatar image LW Glurth · Nov 25, 2016 at 06:47 PM 0
Share

Yes, @Glurth, in my previous reply I stated, "unless I execute in edit mode", but that is not an option for me.

Show more comments
avatar image Adam-Mechtley LW · Nov 25, 2016 at 07:16 PM 0
Share

@LW, @Glurth I can't test it right now, but you could try to ins$$anonymous$$d reassign your cached instance id inside ISerializationCallbackReceiver.OnAfterDeserialize (), ins$$anonymous$$d of inside of inside Awake (), and it shouldn't require ExecuteInEdit$$anonymous$$ode.

avatar image Adam-Mechtley Adam-Mechtley · Nov 25, 2016 at 07:20 PM 0
Share

(That said, this callback will also fire whenever an instance of a prefab is inserted in a scene, whether you use ExecuteInEdit$$anonymous$$ode/Awake or ISerializationCallbackReceiver, so it may not work without some additional smarts)

Show more comments
avatar image Cambesa · Apr 04, 2021 at 12:43 AM 0
Share

To add onto this answer, when you restart unity the id's change and awake is executed. It's a smart move to disable this code when quiting unity so it does not change things you do not want it to change. In my case i cleared a list on duplicate, which was fired hundreds of times when restarting unity so it cleared all items from a list i actually wanted to keep.

avatar image
0

Answer by BubbaRichard · Nov 24, 2016 at 04:24 AM

I don't know if this will help but if you try if (Event.current.commandName == "Duplicate" && Event.current.type == EventType.ExecuteCommand) { Debug.Log(Selection.activeTransform.name); Event.current.Use(); } 1) only check the execute command 2) calling Event.current.Use(); 3) and checking the Selection.activeTransform instead of the activeGameObject you will cancel the duplicate and the Selection.activeTransform will give you the selected object.

The major difference I notice is the activeTransform and the Use() Regards, Bubba

Comment
Add comment · Show 3 · 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 christoph_r · Nov 24, 2016 at 01:31 AM 0
Share

Please format your code.

avatar image BubbaRichard christoph_r · Nov 24, 2016 at 08:15 PM 0
Share

It is formatted when I go to edit.

avatar image Bunny83 BubbaRichard · Nov 25, 2016 at 01:38 PM 1
Share

No, it's not. Please take a look at the site navigation guide that is mentioned in the side panel on the right. About half way down you can find a "tutorial" how to format code properly.

There's even a live-preview below the editing area where you can see it's not formatted. In short a code block need to be indented 4 spaces on each line and needs an empty line before and after the code block. This can be achieved by simply selecting the whole code and pressing the "101/010" button which will ensure those properties.

avatar image
0

Answer by LW · Nov 24, 2016 at 07:16 PM

I have submitted a bug for this. Thank you @Bunny83 and @Adam-Metchley for helping dig around in the editor with me. I can confirm that Event.current.commandName is empty when using the Context menu.

Comment
Add comment · Show 3 · 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 BubbaRichard · Nov 24, 2016 at 10:58 PM 0
Share

I managed to reproduce your issue in a Editor/$$anonymous$$onoBehaviour. I believed I fixed it by adding [@ExecuteInEdit$$anonymous$$ode()] to both. (Tried a number of things) All other code was as I mentioned above.

Regards, Freddie Richard

avatar image LW BubbaRichard · Nov 25, 2016 at 01:22 PM 0
Share

@BubbaRichard thank you for the heads-up! Unfortunately, that workaround has other 'costs' that I'm not certain are good for the project. The fix isn't available to us I believe it has to be fixed internally. But I appreciate the insight!

avatar image Adam-Mechtley · Nov 25, 2016 at 10:10 AM 1
Share

Thanks@LW! I can see 854480 in the bug tracker, which looks like it's probably your case

avatar image
0

Answer by Ng0ns · Jan 02, 2020 at 10:24 PM

I needed to generate new GUID when object was duplicated (it already does so if dragged in as new). So in the GUID component I did this.

     void OnValidate()
     {
         Event e = Event.current;
 
         if (e != null)
         {
             if (e.type == EventType.ExecuteCommand && e.commandName == "Duplicate")
             {
                 GenerateGUID();
             }
         }
     }
Comment
Add comment · Show 1 · 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 Ziplock9000 · Dec 15, 2021 at 12:20 AM 0
Share

I need this for the same reason as you. The solution still seems very hacky (not your fault). There should be a OnDuplicate event exposed.

Also, I had to swap EventType.ExecuteCommand for EventType.Used for it to work from the Edit menu and CTRL-D. Unity 2020.2.7f1.

 void OnValidate()
 {
     Event e = Event.current;
 
     if (e?.type == EventType.Used && e.commandName == "Duplicate")
     {
         id = Guid.NewGuid();
     }
 }

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

70 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

"User is Dragging the Transform Gizmo" in Editor 0 Answers

Detect when project is saved 1 Answer

Event when exiting PolygonCollider2D edit mode 1 Answer

Steal keyboard event Alpha0-9 and disable Unity editor hotkey in custom editor script 1 Answer

Unity UI 4.6 - Programmatically adding events - EventTrigger.delegates is null 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