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
5
Question by homer_3 · Jun 10, 2018 at 06:49 PM · editorheirarchy

Duplicating object in hierarchy sends it to the bottom?

When I duplicate an object in the scene hierarchy, the newly created object gets sent all the way to the bottom of the list of objects. Then I have to drag it all the way back up to be next to the object I duplicated, since usually I want to group them together. Is there a way to duplicate it so it gets put next to the object I'm duplicating automatically?

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

4 Replies

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

Answer by bakir-omarov · Jun 10, 2018 at 07:36 PM

I loved this question! You made my day dude! You can write custom scripts for Unity Editor, for more information: https://docs.unity3d.com/ScriptReference/MenuItem.html


And this is simple code, that will allow you Duplicating selected GameObject, and instantly making it as a child! Is that great, isn't it? I love Unity! :D And i added Shortcut for you, just select GameObject and tap CTRL+SHIFT+D , bingo!


 using UnityEditor;
 using UnityEngine;
 
 public class UnityAnswers_CustomUnityEditorDuplicator : MonoBehaviour {
 
     [MenuItem("Editor Extensions/Duplicate Selected and make it as a child #%d")]
     static void DoSomethingWithAShortcutKey()
     {
         Object prefabRoot = PrefabUtility.GetPrefabParent(Selection.activeGameObject);
         if (prefabRoot != null)
             PrefabUtility.InstantiatePrefab(prefabRoot);
         else
             Instantiate(Selection.activeGameObject, Selection.activeGameObject.transform.position, Selection.activeGameObject.transform.rotation, Selection.activeGameObject.transform);
         Debug.Log("Sir, i duplicated and made it as my child!");
     }
 }
 







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 homer_3 · Jun 10, 2018 at 08:30 PM 0
Share

Thanks. Wasn't exactly what I needed, but I was able to modify it to do what I wanted.

     [$$anonymous$$enuItem("Editor Extensions/Duplicate Selected and make it as a sibling #%d")]
     static void DoSomethingWithAShortcut$$anonymous$$ey()
     {
         GameObject duped = Instantiate(Selection.activeGameObject, Selection.activeGameObject.transform.position, Selection.activeGameObject.transform.rotation);
         duped.transform.SetSiblingIndex( Selection.activeGameObject.transform.GetSiblingIndex() + 1);
     }


avatar image bakir-omarov homer_3 · Jun 10, 2018 at 09:07 PM 0
Share

Yeap, my bad:D I updated your code with parenting, because if you will duplicate some child, it will not duplicated right under original GameObject, but in root of hierarchy. So it is the best code:


 using UnityEditor;
 using UnityEngine;
 
 public class UnityAnswers_CustomUnityEditorDuplicator : $$anonymous$$onoBehaviour {
 
     [$$anonymous$$enuItem("Editor Extensions/Duplicate Selected and make it as a sibling #%d")]
     static void DoSomethingWithAShortcut$$anonymous$$ey()
     {
         GameObject duped = Instantiate(Selection.activeGameObject, Selection.activeGameObject.transform.position, Selection.activeGameObject.transform.rotation, Selection.activeGameObject.transform.parent);
         duped.transform.SetSiblingIndex(Selection.activeGameObject.transform.GetSiblingIndex() + 1);
     }
 }
 

avatar image
1

Answer by r_chevallier · Nov 11, 2018 at 03:14 PM

Hello, Can you modify the script so the duplicate is STILL a instance of a prefab?

If so,

Thanks a Bunch!!!

and Sorry, posted this as an answer.

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 shavemadox · Dec 27, 2019 at 08:43 AM 0
Share

EDIT: I've fixed some bugs and provided the entire script below.

I'm sorry that this is over a year late, but I believe I've figured this portion out as well:

 using UnityEditor;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Text.RegularExpressions;
 
     public class DuplicateAdjacently : $$anonymous$$onoBehaviour
     {
     
         [$$anonymous$$enuItem("Editor Extensions/Duplicate Adjacently #%d")]
         static void Duplicate()
         {
             GameObject selectedObject = Selection.activeGameObject;
             GameObject prefabParent = PrefabUtility.GetCorrespondingObjectFromSource(Selection.activeGameObject);
     
             // Decide on new name
             string pattern = "\\d+$";
             string objectIndex = Regex.$$anonymous$$atch(selectedObject.name, pattern).Value;
             int indexNumber = int.Parse(objectIndex);
             indexNumber++;
             string incrementedIndex = indexNumber.ToString();
             prefabParent.name = Regex.Replace(selectedObject.name, pattern, incrementedIndex);
     
             // Create new object
             GameObject duplicatedObject = PrefabUtility.InstantiatePrefab(prefabParent) as GameObject;
             Undo.RegisterCreatedObjectUndo(duplicatedObject, "Duplicate Adjacently");
             duplicatedObject.SetActive(selectedObject.activeSelf);
             duplicatedObject.transform.parent = selectedObject.transform.parent;
             duplicatedObject.transform.localPosition = selectedObject.transform.localPosition;
             duplicatedObject.transform.localRotation = selectedObject.transform.localRotation;
             duplicatedObject.transform.localScale = selectedObject.transform.localScale;
             duplicatedObject.transform.SetSiblingIndex(selectedObject.transform.GetSiblingIndex() + 1);
             Selection.activeGameObject = duplicatedObject;
         }
     
     }

Thanks much!

avatar image huulong · May 10 at 02:48 PM 0
Share

Tip: to avoid the manual Regex and honor Project Settings > Editor > Numbering Scheme, use GameObjectUtility.GetUniqueNameForSibling(selectedObject.transform.parent, selectedObject.name) instead.

Also, technically you're renaming the instance, not the prefab, so set the name with duplicatedObject.name = GameObjectUtility.GetUniqueNameForSibling(selectedObject.transform.parent, selectedObject.name);

avatar image
1

Answer by huulong · May 10 at 07:00 PM

Combining ideas from https://answers.unity.com/questions/168580/how-do-i-properly-duplicate-an-object-in-a-editor.html (general duplication) and answers here (setting sibling index), I wrote an editor script that supports working in Prefab edit mode and increments the suffix number based on the current Numbering Scheme setting.


I copied the script below but really, Unity Answers is not fit for those long scripts, I think a forum thread would be better (esp. if we bring gradual improvements). I don't see such a thread on Unity forums right now, so I'll just be posting here for now, but if myself or one of you wants to bring further improvements to it, I suggest we open a new thread on the forums and put them there.


In the meantime, I'll put a link to my public repo so there is always the latest version: https://bitbucket.org/hsandt/unity-commons-editor/src/develop/DuplicateGameObjects.cs


and the current script as of 2022-05-10 below so it's accessible directly on this page:


 // DuplicateGameObjects.cs
 
 // References:
 // - ReplaceGameObjects.cs in same folder for prefab linking and support for additive scenes
 // - https://answers.unity.com/questions/168580/how-do-i-properly-duplicate-an-object-in-a-editor.html
 //   (Anisoropos's answer)
 
 using System.Collections.Generic;
 using System.Linq;
 using UnityEditor;
 using UnityEditor.SceneManagement;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public static class DuplicateGameObjects
 {
     [MenuItem("Edit/Duplicate Below %#d", priority = 120)]
     private static void DuplicateSelectionBelow()
     {
         PrefabStage currentPrefabStage = null;
 
         // Check current stage
         Stage currentStage = StageUtility.GetCurrentStage();
         if (currentStage is PrefabStage prefabStage)
         {
             // Prefab edit mode
             currentPrefabStage = prefabStage;
         }
         else if (currentStage is not MainStage)
         {
             // Not Prefab edit mode nor Main scene, must be a custom stage
             Debug.LogWarning("Duplicate Below is not supported in custom stages");
             return;
         }
 
         var clones = new List<GameObject>();
 
         // Note that Selection.transforms, unlike Selection.objects, only keeps the top-most parent
         // if you selected both a parent and a direct or indirect child under it.
         // But since duplicating children modifies the parent content, it means that we would get different results
         // when duplicating the parent or the child first, so it's more stable to just ignore children.
         // "Prefab Mode in Context" pseudo-game-object is also ignored by Selection.transforms,
         // unlike Selection.objects, so it's safer on that side too.
         foreach (Transform selectedTransform in Selection.transforms)
         {
             GameObject selectedGameObject = selectedTransform.gameObject;
 
             if (currentPrefabStage != null && selectedGameObject == currentPrefabStage.prefabContentsRoot)
             {
                 // Prefab root is selected in Prefab Stage
                 // In a prefab, we cannot duplicate the root under itself, since it must have no siblings,
                 // so skip it. And since Selection.transforms ignores children, we know it's the only selection,
                 // so just break.
                 break;
             }
 
             // Get new game object name following Project Settings > Editor > Numbering Scheme
             string newGameObjectName = GameObjectUtility.GetUniqueNameForSibling(selectedTransform.parent,
                 selectedGameObject.name);
 
             GameObject clone;
 
             // Support prefab instances
             GameObject prefab = PrefabUtility.GetCorrespondingObjectFromSource(selectedGameObject);
             if (prefab != null)
             {
                 // Create another prefab instance under same parent as duplicated object
                 // The stage will be set later with PlaceGameObjectInCurrentStage, the parent can still be set now.
                 // If working on the Main Stage, the scene will also be set later with MoveGameObjectToScene,
                 // so don't bother passing the Scene instead of the parent Transform when selectedTransform.parent
                 // is null.
                 clone = (GameObject)PrefabUtility.InstantiatePrefab(prefab, selectedTransform.parent);
                 PrefabUtility.SetPropertyModifications(clone, PrefabUtility.GetPropertyModifications(selectedGameObject));
             }
             else
             {
                 // The duplicated object is not a prefab, create a standard clone under the same parent
                 clone = Object.Instantiate(selectedGameObject, selectedTransform.parent);
             }
 
             // Place clone in current stage
             // This only matters when editing in Prefab Mode
             StageUtility.PlaceGameObjectInCurrentStage(clone);
 
             // When selected object is at scene root (only possible in Main Stage, not Prefab Stage,
             // since we do nothing in case root is selected, but checking it just in case),
             // it will be placed in the active scene by default, so move it to the same scene as the selected object
             if (currentPrefabStage == null && selectedTransform.parent == null)
             {
                 SceneManager.MoveGameObjectToScene(clone, selectedTransform.gameObject.scene);
             }
 
             // Move clone right under selected object
             // This works even with multiple selection under the same parent as GetSiblingIndex is reevaluated
             // after the last child insertion
             clone.transform.SetSiblingIndex(selectedTransform.GetSiblingIndex() + 1);
 
             // Rename clone with Numbering Scheme
             clone.name = newGameObjectName;
 
             Undo.RegisterCreatedObjectUndo(clone, "Duplicate below");
 
             clones.Add(clone);
         }
 
         // Select new objects, if any
         if (clones.Count > 0)
         {
             Selection.objects = clones.Cast<Object>().ToArray();
         }
     }
 }
 



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 MUGIK · May 28 at 11:13 PM 0
Share

HUGE!!!!!!

avatar image
0

Answer by Calm-Chen · Oct 31, 2018 at 01:59 PM

Thank you both of you

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

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

119 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 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

I want to Highlight an object in the hierarchy without selecting it (just the visual effect) NOT USING PING 0 Answers

Is there any way to create folders in the heirarchy to group objects? 1 Answer

Object changes position/rotation, when moved (in/out of parent) in the heirarchy in the editor! 0 Answers

Highlighting an object in the heirarchy 2 Answers

Player slows down unless selected before hitting play in editor 1 Answer


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