Creating buttons in a for loop

Godot Version

v4.2.1.stable.mono,official

Question

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);
		}
	}

Every button now prints the following:

Shouldn’t they print 0, 1, 2, 3 etc?

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.

1 Like

Ah thanks! I now understand what happens.

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);
		}
	}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.