+5 votes

I use Godot 3.0.6
I would like to Put a Field that the user of my game can fill with integeters only.
LineEdit and TextEdit are both usefull for text but not for integers.
Would be nice to have a floating Field too.

Only parsing is not an option since i absolutely need an integer
I don't know if it exists a way to do it or if i need to create a plugin don't know exactly how to do it.

in Engine by (27 points)

2 Answers

+8 votes
Best answer

You can use a SpinBox node which accepts only integers or floats (depending on the step value you specified).

by (12,893 points)
selected by

Actually, this is a better answer. I was so blinded because the question mentioned LineEdit that i didn't thinl of that!

+5 votes

Hi, for doing an integer field, you can modify the lineedit. Just add a LineEdit node to your scene, and attach this script to it:

GODOT 3.0.6

extends LineEdit

var regex = RegEx.new()
var oldtext = ""

func _ready():
    regex.compile("^[0-9]*$")

func _on_LineEdit_text_changed(new_text):
    if regex.search(new_text):
        oldtext = new_text
    else:
        text = oldtext
    set_cursor_position(text.length())

func get_value():
    return(int(text))

BE SURE THAT YOU CONNECT LineEdit's signal text_changed TO FUNCTION ON LineEdit _onLineEdit_text_changed.

GODOT 3.1

extends LineEdit

var regex = RegEx.new()
var oldtext = ""

func _ready():
    regex.compile("^[0-9]*$")

func _on_LineEdit_text_changed(new_text):
    if regex.search(new_text):
        text = new_text   
        oldtext = text
    else:
        text = oldtext
    set_cursor_position(text.length())

func get_value():
    return(int(text))

What i'm doing here, is first declaring a regular expresion that only accepts numeric input. When text changes, you check that the text is numeric. If so, you write that text, if not you keep old text. With get_value function you can get the integer value.

by (3,505 points)

BTW, i've tested it on godot 3.1 beta 2, cause i dont have currently godot 3.0.6... if it does not work i'll download that version and try!

NVM, edited for solution in both versions, tested and works in my pc.

Thanks for the help didnt knew the existence of regex
in fact it's pretty simple when you use that tool

you are welcome!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.