📗
【Unity】TagSelector属性: 変数を直接Tagプルダウンにする
はじめに
初めての方も、そうでない方もこんにちは!
現役ゲームプログラマーのたむぼーです。
自己紹介を載せているので、気になる方は見ていただければ嬉しいです!
今回は
Unityの属性で変数を直接Tagプルダウンにする
方法について紹介します
処理全体
TagSelectorAttribute.csとTagSelectorDrawer.csの2つ作成します。
TagSelectorAttributeは任意のフォルダに格納します。
TagSelectorDrawerはEditorフォルダに格納してください。
TagSelectorAttribute.cs
using UnityEngine;
public class TagSelectorAttribute : PropertyAttribute
{
}
TagSelectorDrawer.cs
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(TagSelectorAttribute))]
public class TagSelectorDrawer : PropertyDrawer
{
/// <summary>
/// OnGUI
/// </summary>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.propertyType != SerializedPropertyType.String)
{
EditorGUI.PropertyField(position, property, label);
EditorGUI.LabelField(position, "Use [TagSelector] with a string field.");
return;
}
EditorGUI.BeginProperty(position, label, property);
// 現在のタグ
string currentTag = property.stringValue;
// タグリストを取得
string[] tags = UnityEditorInternal.InternalEditorUtility.tags;
// ドロップダウンを作成
int index = Mathf.Max(0, System.Array.IndexOf(tags, currentTag));
index = EditorGUI.Popup(position, label.text, index, tags);
// 値を更新
property.stringValue = tags[index];
EditorGUI.EndProperty();
}
}
#endif
使い方
Example.cs
using UnityEngine;
public class Example : MonoBehaviour
{
[SerializeField, TagSelector]
private string _tag;
}
さいごに
LayerSelector属性についての記事も書きました
興味あれば使ってみてください!
Discussion