How to pass the button text to another method

Godot Version

4.5.1.stable

Question

I am trying to pass the text of a button from one method to another, but it doesn’t seem to update for some reason. I determined this was the issue with print statements. In both print statements below, no city name is shown in the Output. I’m not sure why the btn.text is not passing to purchase_city_access tho.

func _ready():
	populate_cities()

func populate_cities():
	for key in Globals.cities:
		var btn = Button.new()
		btn.icon = CITY
		btn.text = str(key)
		btn.flat = true
		btn.alignment = HORIZONTAL_ALIGNMENT_LEFT
		btn.position = map_to_local(Globals.cities[key][0])
		print(btn.text)
		btn.pressed.connect(purchase_city_access.bind(btn.text))
		add_child(btn)

func purchase_city_access(city_name: String):
	print(city_name)
    #Do stuff

The bind is taking btn.text which is a String so it is copied to the bind, not referenced; if the button’s text is changed the bind will stay the same. You could bind the button node itself instead which will be referenced.

1 Like

I changed the code to following but unfortunately, I still don’t see anything in the output:

func _ready():
	populate_cities()

func populate_cities():
	for key in Globals.cities:
		var btn = Button.new()
		btn.icon = CITY
		btn.text = str(key)
		btn.flat = true
		btn.alignment = HORIZONTAL_ALIGNMENT_LEFT
		btn.position = map_to_local(Globals.cities[key][0])
		print(btn.text)
		btn.pressed.connect(purchase_city_access.bind(btn))
		add_child(btn)

func purchase_city_access(btn: Button):
	var city_name = btn.text
	print(city_name)

My apologies everyone, I was able to figure it out.