+1 vote

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

var i = 0
var arg = []
arg.resize(2)

while(i <= (options - 1)):
  var button = Button.new()
  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?

in Engine by (101 points)

1 Answer

+2 votes
Best answer

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 = Button.new()
    i = i + 1
    # Create a new binding at every loop because arguments differ
    button.connect("pressed", self, "ButtonPressed", [button, uniqueStuffFromJson])
    ...
by (29,120 points)
selected by

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: https://www.reddit.com/r/godot/comments/68n4tb/whats_best_way_to_generate_automatically_new/

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.