Unity一鍵複製貼上物件的所有元件和引數
阿新 • • 發佈:2018-12-20
Unity開發中,你如果想要把某個物件的元件全部都拷貝到新的物件上,除了一個個複製貼上元件,還要修改元件中的引數,也就是不斷重複Copy Component 、Paste Component As New、Paste Component Values,實在是一件很麻煩的事,所以想辦法將步驟合起來,直接複製物體上的所有元件、引數,一步搞定。
首先寫一個指令碼,將其放在Editor資料夾下面,程式碼如下:
CopyAllComponent.cs
using UnityEngine; using UnityEditor; using System.Collections; public class CopyAllComponent : EditorWindow { static Component[] copiedComponents; [MenuItem("GameObject/Copy Current Components #&C")] static void Copy() { copiedComponents = Selection.activeGameObject.GetComponents<Component>(); } [MenuItem("GameObject/Paste Current 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); } } } }
可以看到選單欄->GameObject下面這兩行,選中一個物體,Copy Current Components,然後再Paste Current Components,就會發現所有元件以及引數都完整拷貝過來,非常方便。
如果新物體原本就有元件,那麼複製過來不會替換掉原來的元件,如碰撞器,會多複製一個,如果是Rigidbody這種只能掛一個的元件,則不會有效果,即不會修改引數也不會多一個Rigidbody。問題不大。