I was trying to create levelbuttons in a for loop but had some unexpected behaviour.
I recreated the issue with the following code:
public override void _Ready()
{
for (var i = 0; i < 10; i++) {
var button = new Button();
button.Pressed += () => GD.Print($"This is button {i}");
button.Text = $"Button {i}";
button.Position = new Vector2(10, i * 60);
AddChild(button);
}
}
Hello,
Everything is ok, because pressing button will invoke GD.Print($"This is button {i}");
After loop i has value 10.
Adding listener not cache i value.
I added a local variable inside the loop and this seems to work fine.
public override void _Ready()
{
for (var i = 0; i < 10; i++) {
var j = i + 1;
var button = new Button();
button.Pressed += () => GD.Print($"This is button {j}");
button.Text = $"Button {j}";
button.Position = new Vector2(10, i * 60);
AddChild(button);
}
}