Skip to content

Instantly share code, notes, and snippets.

@JakubNei
Last active January 31, 2023 05:41
Show Gist options
  • Save JakubNei/2f1b7abc1727c5608519 to your computer and use it in GitHub Desktop.
Save JakubNei/2f1b7abc1727c5608519 to your computer and use it in GitHub Desktop.
A simple little editor extension to copy and paste all components
/*
A simple little editor extension to copy and paste all components
Help from http://answers.unity3d.com/questions/541045/copy-all-components-from-one-character-to-another.html
license: WTFPL (http://www.wtfpl.net/)
author: aeroson
*/
using UnityEngine;
using UnityEditor;
using System.Collections;
public class ComponentsCopier : EditorWindow
{
static Component[] copiedComponents;
[MenuItem("GameObject/Copy all components %&C")]
static void Copy()
{
copiedComponents = Selection.activeGameObject.GetComponents<Component>();
}
[MenuItem("GameObject/Paste all components %&P")]
static void Paste()
{
foreach (var targetGameObject in Selection.gameObjects)
{
if (!targetGameObject || copiedComponents == null) continue;
foreach (var copiedComponent in copiedComponents)
{
if (!copiedComponent) continue;
UnityEditorInternal.ComponentUtility.CopyComponent(copiedComponent);
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(targetGameObject);
}
}
}
}
@ChessMax
Copy link

ChessMax commented Feb 21, 2020

Why EditorWindow is here? Also, it's better to check copiedComponents == null first and only then iterate over Selection.gameObjects. CopyComponent and PasteComponentAsNew return bool, so it's better to check it either and log warning or error.

@JakubNei
Copy link
Author

JakubNei commented Feb 22, 2020

I agree, feel free to upload improved version and link it here.

@frekons
Copy link

frekons commented Feb 26, 2021

@jaysianchee
Copy link

Hi, is there a demo to show how to use this script in the editor? I have added it to the editor folder in Unity but im not sure how to use it.

@JakubNei
Copy link
Author

JakubNei commented Jun 17, 2022

Hi, is there a demo to show how to use this script in the editor? I have added it to the editor folder in Unity but im not sure how to use it.

You can read up about MenuItem https://docs.unity3d.com/ScriptReference/MenuItem.html to understand it more

@OndrejPetrzilka
Copy link

Would be nice to preserve cross-references between components, but that would be probably way harder to implement.

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