Search Unity

Question Weird TextField behaviour

Discussion in 'UI Toolkit' started by AidanHorton, Jan 4, 2023.

  1. AidanHorton

    AidanHorton

    Joined:
    Apr 25, 2014
    Posts:
    7
    I'm trying to add a chat to my game - but I'm coming across super weird behaviour when trying to what seems like very simple things with the UI Toolkit.

    What I want is to be able to press T, the text field focuses, the placeholder text disappears, and the user can type a message. On enter press again, it submits this message and loses focus.

    So I currently have a TextField in my UI - there are no other text fields.
    When I press enter while my game is running, the TextField focuses itself - it selects any text inside of it and focuses. But what makes this even more weird is that this only happens when I've pressed a key since I last lost focus... This is without any logic or code added by me.

    I've also tried to make it non-focusable, and then focus it with 'textField.Focus()' when I trigger some key (but also setting 'focusable = true;' just before I do that), but that doesn't work either.

    Whatever I do, I cannot get it to focus unless it's just me randomly pressing enter.

    Does anyone know how this system works?
     
  2. HugoBD-Unity

    HugoBD-Unity

    Unity Technologies

    Joined:
    May 14, 2018
    Posts:
    499
    Which version of Unity are you using ?

    The focus logic of the text field is a bit tricky, you may want to refer to this post for more info on how it behaves.
     
  3. AidanHorton

    AidanHorton

    Joined:
    Apr 25, 2014
    Posts:
    7
    I'm using 2022.1.22f1.

    I managed to get it somewhat working in the end - I had to focus the 'unity-text-input' inside of the TextField - but I unfortunately had to put a delay of 0.2 seconds in order so that when the user presses T to trigger focus of the TextField, it doesn't type the letter 't' into the textbox. I can't really see a way around this - I've seen a bunch of threads surrounding it and none of the solutions seemed to work.

    I'm happy enough with the solution for now, but I'm always open to a proper solution :)