Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

環境:

  • 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;
        }
    }
}
hasht
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away