環境:
- Windows 10 Pro (Build 1703)
- Unity 5.6.2p2 (64bit)
Unityのエディタ拡張ではGUI.FocusControl
やEditorGUI.FocusTextInControl
でフォーカスが設定できるが、これらの関数はフォーカスしたいコントロールを配置しているのと同じOnGUI()
内で呼ぶ必要がある。
(GUIの仕組み的に当然と言えば当然?)
従って次の様なコードは機能しない。
wrong.cs
using UnityEngine;
using UnityEditor;
public class TestWindowA : EditorWindow
{
string name = "";
protected void OnGUI()
{
name = GUILayout.TextField(name);
if (GUILayout.Button("Focus"))
{
var window = TestWindowB.GetWindow<TestWindowB>();
window.Focus(name);
}
}
}
public class TestWindowB : EditorWindow
{
public void Focus(string name)
{
GUI.FocusControl(name);
}
protected void OnGUI()
{
GUI.SetNextControlName("a");
GUILayout.TextField("a");
GUI.SetNextControlName("b");
GUILayout.TextField("b");
}
}
どうにかして対象のウィンドウのOnGUI()
内で処理させる必要がある。例えば:
correct.cs
using UnityEngine;
using UnityEditor;
public class TestWindowA : EditorWindow
{
/* 上と同じ */
}
public class TestWindowB : EditorWindow
{
private string nameToFocus;
public void Focus(string name)
{
nameToFocus = name;
}
protected void OnGUI()
{
GUI.SetNextControlName("a");
GUILayout.TextField("a");
GUI.SetNextControlName("b");
GUILayout.TextField("b");
if (nameToFocus != null)
{
GUI.FocusControl(nameToFocus);
nameToFocus = null;
}
}
}