How to pass button meta data through to script on press?

Godot Version

4.4.1

Question

Hi! New to Godot and enjoying it. I have created a Buy Button in a game and in the inspector given it Metadata, e.g. item_name (str), cost (float), etc. My question is how can I access those values in a script and have them passed in?

I see when connecting the pressed() signal to a script you can click on advanced and give optional arguments there, but you don’t seem to be able to name these arguments which isn’t useful to me, they just come as extra_arg_0, incrementing.

The idea would be to create one buy button handler function that can take in parameters about this buttons individual purchase. Maybe something like:

func _on_BuyButton_pressed(button):
	"""One handler for all buy buttons."""
	
	var cost = button.get_meta("cost")
	var item_name = button.get_meta("item_name")
	var brain_bonus = button.get_meta("brain_bonus")
	var physical_bonus = button.get_meta("physical_bonus")
	var popularity_bonus = button.get_meta("popularity_bonus")

But I don’t know how I’d actually pass this function a reference to that button press, any tips? Thank you!

The advanced args are positional, you can name that whatever you like in your handler script if that helps. I think that’s the easiest way to do this.

If you have a number of items like this, you could group them into a class or resource and pass that in instead. You could also create a custom button script (inheriting from button) and export properties that contains the custom values you desire, and then using those properties in the signal handler (or thinking further, maybe an index and/or tag to get the values from some other manager-like object). Lots of ideas, try the signal args first.

You’ll need to Signal.connect() it in code instead if you want to Callable.bind() the button as a parameter when connecting the signal.

Something like:

func _ready():
    var button = $Button
    button.pressed.connect(_on_button_pressed.bind(button))
    
    
func _on_button_pressed(button):
	var cost = button.get_meta("cost")
	var item_name = button.get_meta("item_name")
	var brain_bonus = button.get_meta("brain_bonus")
	var physical_bonus = button.get_meta("physical_bonus")
	var popularity_bonus = button.get_meta("popularity_bonus")
1 Like