How to generate instance of Buttons?

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

Currently I’m using this to generate instance of Buttons:

var i = 0
var arg = []

while(i <= (options - 1)):
  var button =
  arg[0] = button
  arg[1] = uniqueStuffFromJson
  i = i + 1
  button.connect("pressed", self, "ButtonPressed", [arg])

The problem is, all the buttons that are generated in this While loop end up being the same and can’t be clicked, except for the last one.

What’s wrong with this code? And how can I properly generate unique instance of buttons?

:bust_in_silhouette: Reply From: Zylann

You didn’t show all the code involved (because I don’t see any add_child here) but I see something suspicious:

You are creating a new button at every loop, but you assign it to the same arg array, (arg[0]) everytime, so what’s in arg[0] after the while will always be the last generated button.

arg will end up be the same for all your buttons because you did create only one before the loop. To fix it I would suggest the following:

var i = 0

while(i <= (options - 1)):
	var button =
	i = i + 1
	# Create a new binding at every loop because arguments differ
	button.connect("pressed", self, "ButtonPressed", [button, uniqueStuffFromJson])

Thanks! I guess the mistake was obvious to other, because someone also answered it in reddit. He told me to change [arg] into arg, and alter the “func ButtonPressed(arg)” into “func ButtonPressed(button, uniqueStuffFromJson)”.

This is the thread: Reddit - Dive into anything

Qws | 2017-05-02 09:41