Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

how to block space bar input in an InputField.

Discussion in 'Scripting' started by oliuz501, Jan 5, 2020.

  1. oliuz501

    oliuz501

    Joined:
    Dec 30, 2019
    Posts:
    3
    I have one InputField and I want to prevent users typing the space bar in the InputField.

    So I want to write a code to ignore the space bar when it's input.

    if (Input.GetKey(KeyCode.Space))
    {
    I don't know what to write on this area.
    }


    Please give me some helps.
    Thank you.
     
  2. eliyah

    eliyah

    Joined:
    May 4, 2019
    Posts:
    6
    I don't know if this is what you want but I think you can just take the caret position in the input field and delete the spacebar
     
  3. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    I don't think there's a built in way to ignore certain characters in the InputField.

    So one one way to tackle this would be by adding a listener to the onValueChanged event and removing any whitespace from the text (I assume this is why you want to block the space bar).

    Code (CSharp):
    1. public InputField inputField;
    2.  
    3. void Start()
    4. {
    5.     inputField.onValueChanged.AddListener(delegate { RemoveSpaces(); });
    6. }
    7.  
    8. void RemoveSpaces()
    9. {
    10.     inputField.text = inputField.text.Replace(" ", "");
    11. }
     
  4. oliuz501

    oliuz501

    Joined:
    Dec 30, 2019
    Posts:
    3
    Thank You So Much!!