The following scripts job is to scan the given directory and find out how many files(or characters) are in it. Then it creates a number of buttons equal to the total number of files. Currently my problem is that i have no way knowing which button is pressed during run time.
extends Control
#number of characters to be imported
var characters = 0
#file names of all avalible chararters
var files = []
#buttons associated with said characters
var array = []
# Called when the node enters the scene tree for the first time.
func _ready():
scan_directory()
populate()
setup()
#scans for the number of characters in the folder
func scan_directory():
var current = ""
var dir = DirAccess.open("res://Characters/")
dir.list_dir_begin()
current = dir.get_next()
while current != "":
files.push_back(current)
current = dir.get_next()
print(files)
characters = files.size()
func setup():
var x = 0
for i in characters:
var but = array[x]
var path = "res://Characters/" + files[x] + "/"+ files[x] + ".gd"
var char = load(path)
var dic = char.import()
x += 1
#creates buttons equal to the number of characters
func populate():
var x = 100
var y = 100
var texture = Texture2D.new()
texture = load("res://img/button.jpg")
for i in characters:
var but = Button.new()
var path = load("res://Scripts/Character_Select.gd")
add_child(but)
but.pressed.connect(self.export)
but.set_position(Vector2(x,y))
but.set_button_icon(texture)
x += 250
if x > 1250:
x = 100
y += 250
array.push_back(but)
print(array)
func export():
var temp = self.get_instance_id()
print("Current id: " + str(temp))
So im currently looking for a way to either have the button pass a varible when clicked or be able to know the instance id of the button that was clicked so i can compare it to know buttons in the array.
Any help is appreciated.
When you connect to the signal:
but.pressed.connect(self.export)
What you are passing is a Callable
created from the method export
. You can bind
arguments to it, like this:
but.pressed.connect(self.export.bind(1))
Then when the signal is emitted, it will pass that as argument to the method export
. You, of course, need a parameter to receive it, for example:
func export(data):
prints(data)
# ...
In your case, you probably want to pass the iterator variable. This is the idea:
for i in blahblahblah:
# ...
# stuff
# ...
but.pressed.connect(self.export.bind(i))
# ...
# other stuff
# ...
Since each time it would be binding a different value, this allows you know which one it is.
Of course, you can bind something else if you prefer.