How to improve it

Godot Version

4.3

Question

Can someone text how to improve it, please?

func _input(event):
	if Input.is_key_pressed(KEY_1):
		currect_building = 0
	elif Input.is_key_pressed(KEY_2):
		currect_building = 1
	elif Input.is_key_pressed(KEY_3):
		currect_building = 2
	elif Input.is_key_pressed(KEY_4):
		currect_building = 3

``

i guess one way could be the following:

func _input(event):
	for key in [KEY_1, KEY_2, KEY_3, KEY_4]:
		if Input.is_key_pressed(key):
			currect_building = key - 49 # since KEY_1 = 49 -> correct_building = 0

This works because KEY_1 to KEY_4 have a difference of exactly 1.

If you want a more general way of doing this you can do the following:

func _input(event):
	var keys = [KEY_X, ...]
	for key in keys.size():
		if Input.is_key_pressed(keys[key]):
			currect_building = key

This way will assign 0 to the first key in the list, 1 for the second value in the list, and so on

1 Like