Gdscript creating Buttons for ScrollContainer

Godot Version 4.6

This is driving me insane because it should be extremely simple!

I’m trying to dynamically create a scrollbar with several buttons created with gdscript

However, when I run it, it only shows the button for the last item "fourth"in the Array. It almost seems like each new button created just replaces the one from the previous iteration.

You’re half correct. You’re actually only creating one button (via Button.new()) and then overriding its values sequentially in the for-loop. The 4th item is the last in the list so that’s the one being shown.

Since you are never creating and assigning a new button to newbutton, the newbutton variable will always contain a reference to the same button instance.

To fix your issue, create more buttons by moving var newbutton = Button.new() inside the for-loop.


I hope you can see why this fixes the issue. If not, feel free to ask any questions.

THANK YOU SO MUCH!

Okay, so I had a more complex version of this script put in my process function which worked just fine so I was getting exasperated. When you suggested putting the new button variable in the for loop, I think for my process function it was constantly recreating the new button variable for every frame and that’s why it worked there and not in the _ready function immediately.

If you’re ever in doubt about how your code works, just read it line for line and interpret what would happen. You can only do so much with speculative guesswork. If there is something about your own code you don’t understand, you are obligated to find out – for yourself and for others.

Happy coding!