How to get input from a button and fill an array with the sequence of the input?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jellyfish

Hello guys, im a super noob in programming, plz help
I need to get input from 4 buttons then fill an array with the sequence of the input
I connected the button to the script and got a func _on_pressed, but i dont know how to wait for the input calling that function.
On my head i need to run the func _on_pressed inside another function but i dont know how it works
sequence[0] = input of any of the 4 buttons sequence[1] = ...
I cant figure it out

:bust_in_silhouette: Reply From: Philip Whitfield

if I understand you correctly, you are trying to check what button sequence was pressed after 4 button presses? you can create an array and fill it up with each press.

var button_buffer:Array = []
var button_buffer_index:int = 0


func onpress():
	button_buffer[button_buffer_index] = input of button
	button_buffer_index = button_buffer_index + 1
	
	if button_buffer_index == 4:
		# access the last 4 buttons and analyze
		button_buffer[0]
		button_buffer[1]
		button_buffer[2]
		button_buffer[3]

thx for the help,
I had to set the array elements to null, then i worked
var button_buffer:Array = [null, null, null, null]

Jellyfish | 2020-03-03 23:01

yes of course. My bad. otherwise you would have been writing to a non existing index.

Philip Whitfield | 2020-03-04 08:10

:bust_in_silhouette: Reply From: jgodfrey

Here’s another option (depending on some details that are unclear in your original description). Create 4 buttons, wire them all to the same signal handler, and pass the button itself as an arg.

Add the button’s name to an array when it’s pressed. When the array contains 4 elements, print it out, and clear it for the next group of 4 buttons.

It’s not clear whether you have 4 buttons or 1 button. Also, it’s not clear what you want to store about the button when it’s pressed, though since you have the button itself in the _onButtonPressed handler below, you can get anything you want (name, group, text, …). Here’s some sample code:

extends CanvasLayer

var btnPresses = []

func _ready():
	$btnDown.connect("pressed", self, "_onButtonPressed", [$btnDown])
	$btnUp.connect("pressed", self, "_onButtonPressed", [$btnUp])
	$btnLeft.connect("pressed", self, "_onButtonPressed", [$btnLeft])
	$btnRight.connect("pressed", self, "_onButtonPressed", [$btnRight])

func _onButtonPressed(btn):
	btnPresses.append(btn.name)
	if (btnPresses.size() == 4):
		print(btnPresses)
		btnPresses.clear()

thx for the help, but this was kinda complex for me

Jellyfish | 2020-03-03 23:00