You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot 4.1.1:如何批量连接按钮的pressed信号?

在Godot 4.1.1中实现按钮信号的批量连接

一、实现每个按钮对应单独处理函数的需求

你原本想让每个按钮连接到对应的on_pressed_button_1到on_pressed_button_9函数,在Godot 4里可以通过获取方法引用的方式实现循环连接,代码如下:

# 假设buttonArray是包含1到9的数组
for i in buttonArray:
    # 获取对应处理函数的方法引用
    var callback = self.get_method("on_pressed_button_%d" % i)
    # 获取按钮节点
    var button = get_node("button%d" % i)
    # 连接信号
    button.pressed.connect(callback)

# 对应的处理函数示例
func on_pressed_button_1():
    print("按钮1被按下")

func on_pressed_button_2():
    print("按钮2被按下")

# ... 以此类推到on_pressed_button_9

二、统一处理函数的方式在Godot 4.1.1中可行(语法有调整)

你提到的旧版统一处理逻辑在4.1.1里仍然能用,但connect方法的参数格式有变化,不需要再传目标节点的字符串,而是直接用Callable结合bind来传递按钮参数,正确代码如下:

func _ready():
    # 遍历按钮组中的所有按钮
    for button in get_tree().get_nodes_in_group("my_buttons"):
        # 绑定按钮作为参数到处理函数
        button.pressed.connect(Callable(self, "_some_button_pressed").bind(button))

func _some_button_pressed(button):
    print("被按下的按钮:", button.name)

另外,也可以用更简洁的语法直接传递带参数的函数引用:

func _ready():
    for button in get_tree().get_nodes_in_group("my_buttons"):
        button.pressed.connect(func(): _some_button_pressed(button))

需要注意的是,用lambda函数时,循环中每次迭代都会创建独立的上下文,不会出现变量捕获的问题。

内容的提问来源于stack exchange,提问作者NitroBlazoide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:35:08