(:3[kanのメモ帳]

個人ゲーム開発者kan.kikuchiのメモ的技術ブログ。月木更新でUnity関連がメイン。

(:3[kanのメモ帳]


本ブログの運営者kan.kikuchiが個人で開発したゲームです!

    

コンポーネントやその値のコピーとペーストをプログラムから行う方法【Unity】【エディタ拡張】


このエントリーをはてなブックマークに追加



この記事でのバージョン
Unity 2021.3.4f1


はじめに

UnityではInspectorの⁝からコンポーネントをコピーしたりペーストしたり出来ますが、


今回はこれをプログラムから行う方法の紹介です!


UnityEditorInternal.ComponentUtility

コンポーネント関連の操作はUnityEditorInternalのComponentUtilityというクラスを使います。

なお、UnityEditorInternalという名前から分かるようにエディタ専用です。


実際に使ってみると以下のようにそれぞれメソッドを一つ実行するだけ。

//コンポーネントの値をコピー
UnityEditorInternal.ComponentUtility.CopyComponent(transform);

//コピーしたコンポーネントの値を上書き
UnityEditorInternal.ComponentUtility.PasteComponentValues(transform);

//コピーしたコンポーネントを新たに追加
UnityEditorInternal.ComponentUtility.PasteComponentAsNew(gameObject);


ちなみにコンポーネントの移動も出来ますし、

//コンポーネントを一つ上げる
UnityEditorInternal.ComponentUtility.MoveComponentUp(transform);

//コンポーネントを一つ下げる
UnityEditorInternal.ComponentUtility.MoveComponentDown(transform);


DestroyComponentsMatchingやReplaceComponentsIfDifferentといった

Inspectorからは出来ない処理も用意されています。