夜風のMixedReality

xRと出会って変わった人生と出会った技術を書き残すためのGeekなHoloRangerの居場所

UnityEditor拡張でオブジェクトのレイアウトを行う機能を実装する その③UnityEditorウィンドウでEnum型のフィールドを定義する

本日はUnity枠です。

今回はObjectCollectionを開発していきます。

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

redhologerbera.hatenablog.com

ここまでで次のように平面状にオブジェクトを配置する機能までができました。

今回は平面以外のパターンに対応すべくEnum型のフィールドを定義します。

Enum型フィールドの定義

今回は次のようなEnumを定義します。

    public enum CollectionType
    {
        flat,
        circle
    }

flatが現状の平面状に配置、circleが新しく作成するパターンです。

このCollectionTypeをGUIに定義思案す。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;



public class ObjectCollection : EditorWindow
{
    public enum CollectionType
    {
        flat,
        circle
    }
    public CollectionType _CollectionType;
    public GameObject _TargetObj;
    public float _spacing;
    void OnGUI()
    {
        //meshオブジェクトをアタッチするGUI
        GUILayout.Label("Mesh Object", EditorStyles.boldLabel);//ラベルの定義
        _TargetObj = (GameObject)EditorGUILayout.ObjectField("Mesh Object", _TargetObj, typeof(GameObject), true);//フィールドの定義
        _CollectionType = (CollectionType)EditorGUILayout.EnumPopup("Collection Type", _CollectionType);//追加
        _spacing = EditorGUILayout.FloatField("Spacing", _spacing);        
        
        if (GUILayout.Button("Execute"))
        {
            if (_TargetObj != null)
            {
                OnTargetObjectLayoutChanged();
            }
        }
    }
}

上記では_CollectionType = (CollectionType)EditorGUILayout.EnumPopup("Collection Type", _CollectionType);のようにEditorGUILayout.EnumPopupを使用してEnum型を定義しています。

これによってウィンドウは次のようになります。

あとは_CollectionTypeの変数をしようしてSwitch分で処理を分岐することができます。

  public void OnTargetObjectLayoutChanged()
    {
        //_TargetObjの子オブジェクトをすべて取得して等間隔にオブジェクトを配置
        Transform[] children = _TargetObj.GetComponentsInChildren<Transform>();
        
        for (int i = 0; i < children.Length; i++)
        {
            children[i].position = new Vector3(i * _spacing, 0, 0);
            switch (_CollectionType)
            {
                case CollectionType.flat:
                    children[i].position = new Vector3(i * _spacing, 0, 0);
                    break;
                case CollectionType.circle:
                    children[i].position = new Vector3(Mathf.Cos(i * Mathf.PI / 180) * _spacing, 0, Mathf.Sin(i * Mathf.PI / 180) * _spacing);
                    break;
            }
        }
        
    }

これによって平面レイアウトモードと円レイアウトモードを変更できるようになりました。

本日は以上です。