Skip to content

Instantly share code, notes, and snippets.

@karl-
Last active April 17, 2023 17:20
Show Gist options
  • Save karl-/8a7fcdbcf1e2e906d3b4 to your computer and use it in GitHub Desktop.
Save karl-/8a7fcdbcf1e2e906d3b4 to your computer and use it in GitHub Desktop.
Unity Shift-Duplicate
using UnityEngine;
using UnityEditor;
using ProBuilder.Core;
using ProBuilder.EditorCore;
[InitializeOnLoad]
static class ShiftDuplicate
{
static bool m_IsDragging = false;
static ShiftDuplicate()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
static void OnSceneGUI(SceneView scn)
{
Event e = Event.current;
if(!m_IsDragging && e.modifiers == EventModifiers.Shift && e.type == EventType.MouseDrag)
{
m_IsDragging = true;
// probuilder-specific
if(pb_Editor.instance != null && pb_Editor.instance.editLevel == EditLevel.Geometry)
return;
Object[] selection = Selection.GetFiltered(typeof(Transform), SelectionMode.TopLevel);
if(selection != null && selection.Length > 0)
{
Object[] duplicates = new Object[selection.Length];
for(int i = 0, c = selection.Length; i < c; i++)
{
duplicates[i] = Object.Instantiate(selection[i]);
Undo.RegisterCreatedObjectUndo((duplicates[i] as Transform).gameObject, "Shift Duplicate");
}
}
}
if(e.type == EventType.MouseUp || e.type == EventType.Ignore)
m_IsDragging = false;
}
}
@2coder
Copy link

2coder commented Feb 22, 2023

I've improved a little bit on the script, as I needed the functioniality to retain the prefab links.

using UnityEditor;

using UnityEngine;


[InitializeOnLoad]
static class ShiftDuplicate
{
    private static bool _isDragging;

    static ShiftDuplicate()
    {
        SceneView.duringSceneGui += OnSceneGUI;
    }

    static void OnSceneGUI(SceneView scn)
    {
        Event e = Event.current;

        if(!_isDragging && e.modifiers == EventModifiers.Shift && e.type == EventType.MouseDrag)
        {
            _isDragging = true;
            scn.SendEvent(EditorGUIUtility.CommandEvent("Duplicate"));
        }

        if(e.type is EventType.MouseUp or EventType.Ignore)
            _isDragging = false;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment