OnGUI senses Event.current.keyCode multiple times

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.)

                if(chat == true) {
                    if(Event.current.keyCode == KeyCode.Return) {
                        if(sent == false && input != "") {
                            if(input == "/spawn") //DoSomething
                            else //send message to others
                            sent = true;
                            chat = false;
                            input = "";
                        }
                        else chat = false;
                        Event.current.keyCode = KeyCode.None;
                    }
                    else {
                        input = GUI.TextField(new Rect(10, Screen.height - 40, 100, 20), input, 30);
                        sent = false;
                    }
                }
                else if(Event.current.keyCode == KeyCode.Return) {
                    chat = true;
                    Event.current.keyCode = KeyCode.None;
                }

Thank you for your further help and sorry for my English! :slight_smile:

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

1 Like

Yo, Legend mate thanks.

Thank you. this solved my problem too!

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