LoginSignup
0
3

More than 5 years have passed since last update.

Unityのエディタ拡張で他のウィンドウのコントロールをフォーカスする

Posted at

環境:

  • Windows 10 Pro (Build 1703)
  • Unity 5.6.2p2 (64bit)

Unityのエディタ拡張ではGUI.FocusControlEditorGUI.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;
        }
    }
}
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3