Button linked to a boolean input field.

Hello.
I want that when I press a number or comma or dot on my keyboard, it automatically (without clicking the input field) enters a into a input field, then if I press “Enter” ( or a specific key), the input field should empty out and the input should be stored in a variable which I can process further or compare against other variables.
How can I accomplish this task, and furthermore how can I use this variable in another script of another GameObject?
Any help would be appreciated, thank you all in advance!

You can check for keystrokes in an Update() of any object. I wouldn’t necessarily recommend this as it’s dirty code, but hey whatever works for you :slight_smile:

  • void Update()
  • {
  • if (Input.GetKeyDown(“f”))
1 Like

That isn’t exactly what I asked for, I know how to detect key presses. Thank you anyways.

@meikopfaffmann03

I don’t understand why you ask this here, instead of here:

As this is not a 2D question but an UI related question. I bet there are more people who can see and answer your question.

Besides, googling the exact problem gives you the solution… it is already answered.

I am very new to this forum, and I didn’t see this section. Thank you, I will post correctly in the future.

@meikopfaffmann03

This is pretty much what should work I think:

public class GrabInputFocus : MonoBehaviour
{
    [SerializeField] InputField inputField;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Comma))
        {
            Debug.Log("Grab focus");
            inputField.Select();
            inputField.ActivateInputField();
        }
    }
}
1 Like

So you’re trying to achieve autofocus and you want the field('s) to clear after entering the data?
I blieve autofocus can happen with .Select() so you’d put your variable that stores your text field, I’ll call it textField on it like this:

textField.Select();

And to clear it you only need to do this:

textField.Clear();

Now to press any key and it auto-focus on the field, well, you’ll need to code it to do so… You will need to check for literally every single key press within the Update().

void Update()
{
if(Input.GetKeyDown(KeyCode.A)
{
textField.Select();
textField.text = "A";
}
}

And you will need to do this for every possible key entry.

Edit:

Keeping in mind that you would need to concatenate each new letter you enter using textField.text =

You’ll end up having to create an array and store all previously entered chars, and remove deleted, etc… The code I provided will delete the field and place ONLY the new char in it. Just thought you should know.