How is MenuButton node supposed to work

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

I’m using Godot 4 trying to make a personal project but I’m really struggling to make the MenuButton node work. I’ve seen that in previous versions of Godot it was something like:

func _ready():
get_popup.connect("id_pressed", self, "func_name")

I tried that, didn’t work. Error saying ‘self’ was an object and not a callable.
Then I found out there was a new way of doing this:

func _ready():
get_popup.id_pressed().connect(self.func_name())

func func_name(id):
#code

Now here’s my problem: I need the id of the button pressed to make this work. I’ve tried multiple ways and nothing seems to be working.

:bust_in_silhouette: Reply From: Moreus

From Godot Documentation

func _ready():
    var button = Button.new()
    button.text = "Click me"
    button.pressed.connect(self._button_pressed)
    add_child(button)

func _button_pressed():
    print("Hello world!")

you can get id by
int get_instance_id ( ) const in func _button_pressed():?

You can check example of connect here too(if your ID is something else)

get_popup.id_pressed.connect(self.func_name(id))

Moreus | 2023-04-06 09:12

:bust_in_silhouette: Reply From: brainbug
self.func_name !!!

not

self.funce_name() #this will call the function  

self.func_name is the Callable - the function object
connect an signal with the callable

:bust_in_silhouette: Reply From: ld2studio

To use a MenuButton node, you have to add items with the method $MenuButton.get_popup().add_item(“Item 1”, id_1) with id_1 = integer.

When you connect id_pressed to a callable, you retrieve as parameters the id specified previously.

Example :

enum ItemId {
	LEVEL1,
	LEVEL2,
	LEVEL3
}

func _ready():
	menu_button.get_popup().add_item("Level 1", ItemId.LEVEL1)
	menu_button.get_popup().add_item("Level 2", ItemId.LEVEL2)
	menu_button.get_popup().add_item("Level 3", ItemId.LEVEL3)
	menu_button.get_popup().id_pressed.connect(_on_item_menu_pressed)

func _on_item_menu_pressed(id: int):
	print("Item ID: ", id)

Thanks! That worked perfectly. I want to add that it’s not essential to create the items by code, I created them by the engine and it still works.

sauttize | 2023-04-07 03:01

3 Likes