Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.

@aeroson
Copy link
Author

aeroson 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

jaysianchee 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.

@aeroson
Copy link
Author

aeroson 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

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