How to create a button node dynamically and give it functionallity (script)?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SSG2710

I’m trying to create some button nodes dynamically, depending in an array, also I want to give those buttons a script (or something to make them functional).
I haven’t found anything that works for me in other posts.
thanks four your help in advance.

:bust_in_silhouette: Reply From: jason1207

I think this might be helpful:

As for adding button nodes to array, you might want to save button instances as objects and save them to the array.

ok thanks, I will have a look

SSG2710 | 2021-02-12 03:41

not exactly what I needed, but thanks

SSG2710 | 2021-02-12 15:36

:bust_in_silhouette: Reply From: bloodsign

I think I’ve made something like that.
The process is a bit long for this format but It kinda works like this:

  1. Create button instance/scene and add a script to it. Say (res://button.tscn) with script like:
extends Button
var something setget set_something
func set_something(value):
  something = value

  1. Go back to wherever scene you want to dynamically create buttons and on your script. Create the buttons dynamically:
var button_pck = preload("res://button.tscn")
var array = [ "res://chapter1.tscn","res://chapter2.tscn",.....] 
for n in array:
   var button = button_pck.instance()

This way, I could just keep adding to the array and buttons should be dynamically created and each button event would be unique(based on the array contents or whatever I passed to it anyways)

exactly what I was searching for, thank you

SSG2710 | 2021-02-12 16:55