Search Unity

Resolved How to force focus on a text field? My solution prevents typing for some reason. 2020.3.7f1

Discussion in 'Immediate Mode GUI (IMGUI)' started by PowerJake, Jul 6, 2021.

  1. PowerJake

    PowerJake

    Joined:
    Nov 15, 2019
    Posts:
    64
    I am writing a simple dev console for my game. I do not want the mouse to be necessary to do any action in my game (even cheating) so I want to automatically set the console's command field to always be in focus as long as the console is open. Here is my OnGUI. The important part is highlighted.

    Code (CSharp):
    1. private Vector2 scroll;
    2.     private int outputSize = 200;
    3.     private void OnGUI() {
    4.         if (!showConsole) {return;}
    5.  
    6.         float y = 0f;
    7.        
    8.         // display the output box
    9.         GUI.Box(new Rect(0, y, Screen.width, outputSize), "");
    10.         Rect viewPort = new Rect(0, 0, Screen.width - 30, 20 * commandList.Count);
    11.         scroll = GUI.BeginScrollView(new Rect(0, y + 5f, Screen.width, outputSize - 10), scroll, viewPort);
    12.        
    13.         // display output text in the box
    14.         for (int i = 0; i < outputTextLines.Count; i++) {
    15.             Rect labelRect = new Rect(5, 20 * i, viewPort.width - 100, 20);
    16.             GUI.Label(labelRect, outputTextLines[i]);
    17.         }
    18.         GUI.EndScrollView();
    19.         y += outputSize;
    20.        
    21.         // display text input box and field
    22.         GUI.Box(new Rect(0, y, Screen.width, 30 * scale), "");
    23.         GUI.backgroundColor = new Color(0, 0, 0, 0);
    24.  
    25.         // VVVVVVVVVVVVVVVV The problem section VVVVVVVVVVVVVVVV
    26.         GUI.SetNextControlName("console");
    27.         _input = GUI.TextField(new Rect(10f, y + 5f * scale, Screen.width-20f, 20f * scale), _input);
    28.        
    29.         print(GUI.GetNameOfFocusedControl());
    30.         GUI.FocusControl("console"); // force focus on console while it is open
    31.     }
    I would expect this to automatically force focus on the text entry box every frame it is active but this happens.

    upload_2021-7-6_15-29-0.png

    The typing line cursor thing appears in the text spot (you can't see it in the screenshot), but I am unable to type. The print statement also seems to alternate between outputing "" and "console" as though it is being reset constantly. If I remove the call to FocusControl("console") then my console works just fine, but trying to manage the focus breaks it.

    Got any idea what is going wrong? Thanks!
     
  2. liyueyueniaoguangjun

    liyueyueniaoguangjun

    Joined:
    Oct 17, 2019
    Posts:
    6
    you can try use EditorGUI.FocusTextInControl("console") replace GUI.FocusControl("console");
     
    PowerJake likes this.
  3. PowerJake

    PowerJake

    Joined:
    Nov 15, 2019
    Posts:
    64
    That did it. Thanks!