Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to detect inputfield focus?

Discussion in 'Scripting' started by TheCrake, Aug 7, 2019.

  1. TheCrake

    TheCrake

    Joined:
    Oct 24, 2018
    Posts:
    15
    I have an inputfield where the player can enter numbers. I also use the number keys to activate certain actions. I want to allow the player to type 1, 2, or 3 for example into the input field without it activating the actions normally triggered by pressing 1, 2 or 3 in the main game. I've found a way to detect when the player exits the inputfield, but I cannot find any way to detect when you either start editing or when it is focused. It seems there were some abilities to detect that but they were removed from unity a long time ago. Anyone know the most elegant way to do this? Thanks so much!
     
  2. bentontr

    bentontr

    Joined:
    Jun 9, 2017
    Posts:
    39
    Have you tried out the "isFocused" property on InputField?
     
  3. TheCrake

    TheCrake

    Joined:
    Oct 24, 2018
    Posts:
    15
    I did, It seems like that was removed in an older version of unity and I can't seem to find a syntax that works in 2019.1. Unless I'm just using it wrong?
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    AFAIK there is no event to detect when an input field is focused; you need to constantly check through polling (e.g. in Update) to find out what the current state is.

    I haven't switched to Unity 2019 yet, but InputField.isFocused is still listed in the 2019.1 scripting API and I don't know of any reason it shouldn't work.

    You can also check the value of EventSystem.current.currentSelectedGameObject (in namespace UnityEngine.EventSystems) to see whether the input field is selected. I'm not sure whether "selected" and "focused" are different.
     
  5. TheCrake

    TheCrake

    Joined:
    Oct 24, 2018
    Posts:
    15
    Thanks, I'll try those out.
     
  6. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I just tested it out in 2019.1.7 and 2019.2.0 and they both have it.
    Didn't try to do anything with it, but it shows up in auto complete and compiles fine.
     
  7. TheCrake

    TheCrake

    Joined:
    Oct 24, 2018
    Posts:
    15
    Yes, I got it working, thanks so much everyone. Apparently I needed to check if InputField.isFocused was true, instead I was using it like onClick which is an event you can add a listener to. My apologies everyone, thanks again!