Unity Component批量復制
在制作畢設的程序中,我發現我的角色模型需要替換,但是原角色物體上有很多組件,如果全部在Inspector面板右鍵Copy、Paste很麻煩,所以制作了一個能夠將物體上所有組件一鍵復制粘貼的工具,

將原物體放到左邊,新物體放到右邊,點擊檢測按鈕,

然后點擊Copy按鈕,就會把左邊物體身上的組件(除了Transform組件和Tag、Layer)復制到右邊物體上,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
public class ComponentCopyWindow : EditorWindow
{
private GameObject rootGO;
private List<Component> rootComponents;
private GameObject targetGO;
private List<Component> targetComponents;
[MenuItem("Wonderland6627/ComponentCopyWindow")]
public static void ShowWindow()
{
var window = EditorWindow.GetWindowWithRect<ComponentCopyWindow>(new Rect(0, 0, 700, 350));
}
private void OnEnable()
{
rootComponents = new List<Component>();
targetComponents = new List<Component>();
}
private void OnGUI()
{
GUI.Label(new Rect(200, 0, 500, 20), "將'原始物體'的組件都復制到'復制物體上'(不包括Transform、Tag、Layer)");
GUILayout.Space(20);
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label("原始物體:");
rootGO = EditorGUILayout.ObjectField(rootGO, typeof(GameObject)) as GameObject;
if (rootGO)
{
EditorGUILayout.BeginVertical();
{
GUILayout.BeginArea(new Rect(5, 50, 300, 300), GUI.skin.box);
{
if (GUILayout.Button("檢測物體組件"))
{
rootComponents = rootGO.GetComponents<Component>().ToList();
rootComponents.RemoveAll((comp) =>
{
return comp.GetType() == typeof(Transform);
});
}
if (rootComponents != null && rootComponents.Count != 0)
{
for (int i = 0; i < rootComponents.Count; i++)
{
GUILayout.Label(i + " " + rootComponents[i].GetType().Name);
}
}
}
GUILayout.EndArea();
}
EditorGUILayout.EndVertical();
}
GUILayout.Space(50);
if (rootGO && targetGO)
{
GUI.enabled = (rootComponents.Count != 0);
if (GUI.Button(new Rect(310, 160, 70, 30), "Copy to =>", EditorStyles.toolbarButton))
{
for (int i = 0; i < rootComponents.Count; i++)
{
ComponentUtility.CopyComponent(rootComponents[i]);
ComponentUtility.PasteComponentAsNew(targetGO);
}
targetComponents = targetGO.GetComponents<Component>().ToList();
targetComponents.RemoveAll((comp) =>
{
return comp.GetType() == typeof(Transform);
});
}
GUI.enabled = true;
}
GUILayout.Space(50);
GUILayout.Label("復制物體:");
targetGO = EditorGUILayout.ObjectField(targetGO, typeof(GameObject)) as GameObject;
if (targetGO)
{
EditorGUILayout.BeginVertical();
{
GUILayout.BeginArea(new Rect(5 + 80 + 300, 50, 300, 300), GUI.skin.box);
{
if (targetComponents != null && targetComponents.Count != 0)
{
for (int i = 0; i < targetComponents.Count; i++)
{
GUILayout.Label(i + " " + targetComponents[i].GetType().Name);
}
}
}
GUILayout.EndArea();
}
EditorGUILayout.EndVertical();
}
}
EditorGUILayout.EndHorizontal();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/279997.html
標籤:其他
上一篇:除錯學習【2】
下一篇:頂配售價 18499 元,用上 M1 的 iPad Pro 性能與價格“直逼”電腦,這屆蘋果發布會有你喜歡的嗎?
