Topic was automatically imported from the old Question2Answer platform.
Asked By
Raikish
Hi dear community.
I’m trying to iterate a foreach loop using a for in like in the next example. I need to get the index to multiply the button size and spawn it in the correct spot.
func create_buttons():
delete_buttons()
for i, unit in selected_units: //i gives me an error
if not buttons.has(unit.name):
var but = button.instance()
but.connect_me(self, unit.name)
var offset = 64
but.rect_position = Vector2(buttons.size() * i + offset , $UI/NinePatchRect.rect_size / 2)
$UI/NinePatchRect.add_child(but)
buttons.append(but.name)
I know i can create an var outside the loop and the incrementate but thats ugly.
I’m new in gdscript and python. Any kind of help will be appreciated.
for i in len(selected_units):
var unit = selected_units[i]
#...
I tend to not use range in for loops because although it looks nicer in the Python sense, Godot does not have iterables, which means range returns an array, so if your list is huge it will create an array of that size everytime (impact is negligible for small lists).
Edit: actually this was true in Godot 2 but an exception for for loops might have changed in Godot 3, I’m not exactly sure right now