リストからクラスを選択して、値を変更するような Editor 拡張を作成したとき
戻って他の値を変更しようと他を開いた際に、実際には前の値が入っていないのに見た目上は値が入ってるように見えることがある
これは EditorGUI のフォーカスが外れてないため発生する
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class SampleEditorWindow : EditorWindow { [Serializable] private class Sample { public int IntValue; public string StringValue; public float FloatValue; } [SerializeField] private List<Sample> _list = new List<Sample>(); private int _selectIndex = -1; private void OnGUI() { if (_selectIndex >= 0) { if (GUILayout.Button("Back")) { _selectIndex = -1; GUIUtility.ExitGUI(); } EditorGUILayout.LabelField(_selectIndex.ToString()); _list[_selectIndex].IntValue = EditorGUILayout.IntField("IntValue", _list[_selectIndex].IntValue); _list[_selectIndex].StringValue = EditorGUILayout.TextField("StringValue", _list[_selectIndex].StringValue); _list[_selectIndex].FloatValue = EditorGUILayout.FloatField("FloatValue", _list[_selectIndex].FloatValue); return; } for (var i = 0; i < _list.Count; i++) { if (GUILayout.Button((i + 1).ToString())) { _selectIndex = i; } } if (GUILayout.Button("Add")) { _list.Add(new Sample()); } } }
フォーカスを外す
フォーカスを外すのは簡単で GUI.FocusControl("");
を呼び出せばよい
FocusControl は名前を入れるとフォーカスを指定できますが、空文字を入れることがフォーカスを外すことができます
今回の場合は戻るボタンを押した際にフォーカスを外す処理を呼びだすことで、
別の要素を見た際に前の値が入っていることがなくなります
if (GUILayout.Button("Back")) { _selectIndex = -1; GUI.FocusControl(""); GUIUtility.ExitGUI(); }