How to get char value from _input(event) and add it to a string?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By unknown llama
:warning: Old Version Published before Godot 3 was released.

Hello Everyone,

I have a very simple question this time!

How do I get the char value of a KEY that has been pressed in the _input(event) func and add it to a string?

I see that event.unicode seems to hold the integer value of the key but I cannot find a way to convert that integer into a char so it can be added to a string as a character not a number.

For Example:
If the user presses the ‘a’ key, event.unicode is 97, but I want the “a” to be added to my string, not “97”. In C we could just use char(97), but I cannot find a way to do this in GDScript.


:bust_in_silhouette: Reply From: GlaDOSik

I’m not sure about unicode, but you can use scancode and then convert it to the string with function OS::get scancode string. Dont forget to control the event type.

func _input(event):
	if (event.type == InputEvent.KEY):

Thank you for your time and your answer.

Unfortunately scancodes are only uppercase and get_scancode_string returns full words for some of the codes, like “Shift” and “Space” :frowning:

unknown llama | 2016-03-09 00:00

Unfortunately, that’s true. But you can check the length of string and filter out words like Shift, Space, etc. You can even check the scancode for CapsLock and Shift and use String::to_lower. Here is an example (just for Shift):

func _input(event):
if (event.type == InputEvent.KEY):
	if(OS.get_scancode_string(event.scancode).length() == 1):

GlaDOSik | 2016-03-09 00:28

:bust_in_silhouette: Reply From: umfk
var bla = RawArray([97])



More info

Edit: I do agree that a simpler function for single bytes would be great. You could add an issue on github about it.

Perfect. Thank you for this!

I just discovered the get_string_from_utf8about 10 minutes ago, but was going about it the long way. Took me 4 lines to do what you have done in 1!

You have simplified it for me, thank you.


unknown llama | 2016-03-09 01:06

:bust_in_silhouette: Reply From: ArdaE

Looks a new function was added specifically for this purpose later in 2016:
Add `String char(int ascii)` function to GDScript and Visual Script by bojidar-bg · Pull Request #6692 · godotengine/godot · GitHub

To convert event.unicode to a String, we can now do this: char(event.unicode)