パハットノート

※当サイトではGoogleアドセンス広告を利用しています

Unity エディタ拡張(publicリストの各要素に名前を付ける)

概要

リストや配列をインスペクター上に表示すると通常は「Element0」、「Element1」などのように表示されるがこの表示を変えられないかと考え、エディタ拡張を行った。



プログラム例

あるクラスでの英語のテストの点数を保存するクラス「ScoreTable」を用意し、その中のリスト「scores」に点数を保存するとする。

using System.Collections.Generic;
using UnityEngine;

public class ScoreTable : MonoBehaviour
{
    [SerializeField] public List<int> scores = new List<int>(3);
}


次にクラス「ScoreTableEditor」を用意し、上記のクラスのエディタ拡張を行う。

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

[CustomEditor(typeof(ScoreTable))]
public class ScoreTableEditor : Editor
{
    ScoreTable table;

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        table = target as ScoreTable;
        SetScore();

        serializedObject.ApplyModifiedProperties();
    }

    static List<string> names = new List<string>(3)
    {
        "A",
        "B",
        "C"
    };

    void SetScore()
    {
        //保存されているリストを読み込み
        List<int> scores = table.scores;

        //未設定 or namesと長さが違う場合には0で初期化
        if (scores == null || scores.Count != names.Count)
        {
            scores = new List<int>();
            for (int i = 0; i < names.Count; i++)
                scores.Add(0);
        }

        //表示
        EditorGUILayout.HelpBox("英語のテストの点数", MessageType.None);
        for (int i = 0; i < names.Count; i++)
        {
            scores[i] = EditorGUILayout.IntField(names[i], scores[i], GUILayout.MinWidth(400));
        }

        //入力した値を元のリストに渡す
        table.scores = scores;
    }
}