该篇文章只是实现以下功能
1、实现复制功能 Copy Component
2、实现粘贴功能 Paste Component As New和Paste Component Values
直接上可运行代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
public class CopyComponent : Editor {
static Component[] compoentArr;
[MenuItem("Component Editor/Copy Component")]
static void DoCopyComponent()
{
compoentArr = Selection.activeGameObject.GetComponents<Component> ();
}
[MenuItem("Component Editor/Paste Component")]
static void DoPasteComponent()
{
if (compoentArr == null) {
return;
}
GameObject targetObject = Selection.activeGameObject;
if (targetObject == null) {
return;
}
for (int i = 0; i < compoentArr.Length; i++) {
Component newComponent = compoentArr [i];
if (newComponent == null) {
continue;
}
UnityEditorInternal.ComponentUtility.CopyComponent (newComponent);
Component oldComponent = targetObject.GetComponent (newComponent.GetType ());
if (oldComponent != null) {
if (UnityEditorInternal.ComponentUtility.PasteComponentValues (oldComponent)) {
Debug.Log ("Paste Values " + newComponent.GetType ().ToString () + " Success");
} else {
Debug.Log ("Paste Values " + newComponent.GetType ().ToString () + " Failed");
}
} else {
if (UnityEditorInternal.ComponentUtility.PasteComponentAsNew (targetObject)) {
Debug.Log ("Paste New Values " + newComponent.GetType ().ToString () + " Success");
} else {
Debug.Log ("Paste New Values " + newComponent.GetType ().ToString () + " Failed");
}
}
}
}
}
最后效果:
被我们复制相机的组件信息
粘贴到新创建的游戏体中