unity Editor コンポーネントをソートする SortComponentsWindow.cs

f:id:yasuaki-ohama:20160114003029p:plain:w400

目次

概要

UnityではGameObjectにアタッチしているコンポーネントの順番を入れ替えたい時
「Move Up」「Move Down」をクリックして移動する。
f:id:yasuaki-ohama:20160110115714p:plain:w400
そのため、好きな順番にソートするのが大変です。
なので今回は、簡単にソートができるエディタウィンドウを作成しました。

機能

使い方

以下のサイトからSortComponentsWindow.csをダウンロード
Applyボタンあり(入れ替え後、ボタンを押して反映)
Applyボタンなし(入れ替えると自動で反映)

f:id:yasuaki-ohama:20160110121223p:plain
Unityにドラック & ドロップするとEditorWindowがでてきます
f:id:yasuaki-ohama:20160110123130p:plain:w400
Sort Components Windowをクリック
f:id:yasuaki-ohama:20160110123152p:plain:w400
適当に配置
f:id:yasuaki-ohama:20160110123209p:plain:w400
ソートしたいオブジェクトをドラック & ドロップ
f:id:yasuaki-ohama:20160114004948p:plain:w400
ドラックしてコンポーネントをドラックして入れ替えできる
f:id:yasuaki-ohama:20160114004957p:plain:w400
プレハブも可能

スクリプト

gist.github.com

テストに利用したスクリプト

using UnityEngine;
using System.Collections;

public class Script_1 : MonoBehaviour
{
    public int value_1;
}
using UnityEngine;
using System.Collections;

public class Script_2 : MonoBehaviour
{
    public int value_2;
}
using UnityEngine;
using System.Collections;

public class Script_3 : MonoBehaviour
{
    public int value_3;
}

製作時の問題

「CheckComponentsUpdate ()」を作成した経緯

以下の方法で試したが更新できなかったため手動検知プログラムを作成した

    void OnMouseDown()
    {
        //更新処理
    }

    void OnValidate()
    {
        //更新処理
    }

    private void OnGUI()
    {
        EditorGUI.BeginChangeCheck ();

        ...

        if (EditorGUI.EndChangeCheck ()){
                //更新処理
        }
    }

スクリプトが外れている場合の対処

f:id:yasuaki-ohama:20160111005907p:plain:w300

アタッチしたスクリプト内にある変数の値を表示

f:id:yasuaki-ohama:20160114005012p:plain:w400

m_reorderableList.drawElementCallback = (rect, index, isActive, isFocused) => {
    EditorGUI.LabelField(rect, SrawElementCallback((Object)m_reorderableList.list[index], index));
};

SrawElementCallbackをSrawElementCallbackCustomに変更する

m_reorderableList.drawElementCallback = (rect, index, isActive, isFocused) => {
    EditorGUI.LabelField(rect, SrawElementCallbackCustom((Object)m_reorderableList.list[index], index));
};

やってはいけない操作

SortComponentsWindowで同じプレハブを
「プロジェクト」と「ヒエラルキー」の両方で操作を行うと個数が2倍になります。


1、プロジェクトにあるプレハブをヒエラルキーに置く
2、ヒエラルキーのプレハブをSortComponentsWindowに入れて操作(コンポーネントの複製と削除)
3、プロジェクトのプレハブをSortComponentsWindowに入れて操作(コンポーネントの複製と削除)
4、(2、3)によりヒエラルキーとプロジェクトのプレハブに差分が発生
5、ヒエラルキーのプレハブにプロジェクトの差分が自動で追加(Unityの機能)
結果ヒエラルキーコンポーネントの個数が2倍になる