Search Unity

OnGUI senses Event.current.keyCode multiple times

Discussion in 'Immediate Mode GUI (IMGUI)' started by Tudvari, Dec 23, 2015.

  1. Tudvari

    Tudvari

    Joined:
    Jun 3, 2014
    Posts:
    30
    Hi folks!

    When I hit for example the Return button, OnGUI senses it in multiple runs.
    So for example if I can turn on and off something with enter, when I hut enter it turns on then off then on then off.

    I tried that after it senses the key, I set the key to None.
    Event.current.keyCode = KeyCode.None;

    But for some reason now it turns on, then off. (previous time it was "on off on off")

    I am writing a chat input script, so when the user hits the enter button, an input field comes in, and if he hits enter again, it disappears, and sends it to the other players on the network, if he typed something.
    The chat variable is false when the input field should be hidden, and true when it should be visible.
    The input variable is the message.
    I used the sent variable, because this problem also occur I send the message, and even if I set the input field to "" it sends an empty message too. (because it runs very fast i think.)
    Code (CSharp):
    1.                 if(chat == true) {
    2.                     if(Event.current.keyCode == KeyCode.Return) {
    3.                         if(sent == false && input != "") {
    4.                             if(input == "/spawn") //DoSomething
    5.                             else //send message to others
    6.                             sent = true;
    7.                             chat = false;
    8.                             input = "";
    9.                         }
    10.                         else chat = false;
    11.                         Event.current.keyCode = KeyCode.None;
    12.                     }
    13.                     else {
    14.                         input = GUI.TextField(new Rect(10, Screen.height - 40, 100, 20), input, 30);
    15.                         sent = false;
    16.                     }
    17.                 }
    18.                 else if(Event.current.keyCode == KeyCode.Return) {
    19.                     chat = true;
    20.                     Event.current.keyCode = KeyCode.None;
    21.                 }
    Thank you for your further help and sorry for my English! :)
     
  2. Tudvari

    Tudvari

    Joined:
    Jun 3, 2014
    Posts:
    30
    I got it: I have to check the type of the event, so the IF will be only true if the user pushes the key down.
    Event.current.type == EventType.KeyDown
     
    DylanYasen likes this.
  3. Kittensmasher

    Kittensmasher

    Joined:
    Oct 25, 2013
    Posts:
    1
    Yo, Legend mate thanks.
     
  4. gamedevelopmenttsunami

    gamedevelopmenttsunami

    Joined:
    Oct 1, 2016
    Posts:
    10
    Thank you. this solved my problem too!

    if (Event.current.type == EventType.KeyUp){ ... }