如何连接按钮信号列表? - 戈多 4.1.1

问题描述 投票:0回答:1

我想通过代码连接 9 个按钮的按下信号,但由于 .connect 方法不使用字符串参数(我可以在循环中轻松修改),我不知道如何连接它们中的每一个。

我想做这样的事情:

for i in buttonArray:
    get_node("button%d" %i).pressed.connect("on_pressed_button_%d" %i)

预计它将把 9 个按下信号连接到我的 9 个 on_pressed_button 函数

我发现了一篇关于旧版 Godot 版本的帖子,该版本仅对整个列表使用一个“on_pressed”函数并在参数中获取按钮。

for button in get_tree().get_nodes_in_group("my_buttons"):
    button.connect("pressed", self, "_some_button_pressed", [button])

func _some_button_pressed(button):
    print(button.name)

在实际的 4.1 版本中还可能出现这样的情况吗?

signals godot gdscript godot4
1个回答
0
投票


我能够通过使用 Callables 和

call(String)
函数来解决这个问题。

extends Node2D

func _ready():
    for button in $ButtonList.get_children():
        button.pressed.connect(func(): call("on_pressed_"+button.name) )

func on_pressed_Button1():
    print("1")
func on_pressed_Button2():
    print("2")
func on_pressed_Button3():
    print("3")
func on_pressed_Button4():
    print("4")
func on_pressed_Button5():
    print("5")

这样做是有效的,但要求您为每个按钮提供一个功能,并且对名称敏感(您可以像开始时一样使用索引来解决这个问题)。

© www.soinside.com 2019 - 2024. All rights reserved.