📗

【Unity】LayerSelector属性: 変数を直接Layerプルダウンにする

2025/03/06に公開

はじめに

初めての方も、そうでない方もこんにちは!
現役ゲームプログラマーのたむぼーです。
自己紹介を載せているので、気になる方は見ていただければ嬉しいです!

今回は
 Unityの属性で変数を直接Layerプルダウンにする
方法について紹介します

https://zenn.dev/tmb/articles/1072f8ea010299

処理全体

LayerSelectorAttribute.csとLayerSelectorDrawer.csの2つ作成します。
LayerSelectorAttributeは任意のフォルダに格納します。
LayerSelectorDrawerはEditorフォルダに格納してください。

LayerSelectorAttribute.cs
using UnityEngine;

public class LayerSelectorAttribute : PropertyAttribute
{
}
LayerSelectorDrawer.cs
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;

[CustomPropertyDrawer(typeof(LayerSelectorAttribute))]
public class LayerSelectorDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.propertyType == SerializedPropertyType.Integer)
        {
            // 追加済みのレイヤーを取得("Add Layer" を除外)
            string[] layers = InternalEditorUtility.layers;

            // 現在の値(int)をレイヤー名と対応付ける
            int currentLayerIndex = Mathf.Max(0, System.Array.IndexOf(layers, LayerMask.LayerToName(property.intValue)));

            // インスペクターにドロップダウンを表示
            int selectedLayerIndex = EditorGUI.Popup(position, label.text, currentLayerIndex, layers);

            // レイヤーが変更されたら、対応するレイヤー番号を取得
            if (selectedLayerIndex >= 0)
            {
                property.intValue = LayerMask.NameToLayer(layers[selectedLayerIndex]);
            }
        }
        else
        {
            EditorGUI.LabelField(position, label.text, "Use with int fields only.");
        }
    }
}
#endif

使い方

Example.cs
using UnityEngine;

public class Example : MonoBehaviour
{
    [SerializeField, LayerSelector]
    private int _layer;
}

さいごに

TagSelector属性についての記事も書きました
興味あれば使ってみてください!
https://zenn.dev/tmb/articles/15d9644709b988

Discussion