如何在Godot引擎中通过Lua GDExtension连接Timer超时信号?
Lua GDExtension中正确连接Timer超时信号的方法
问题场景
尝试在附加到Node2D的Lua脚本中连接Timer的超时信号但未成功,原代码如下:
local test = { extends = Node2D, } function test:_ready() function _on_timeout() print("timeout end") end local timer = self:get_tree():create_timer(2) timer:connect("timeout", self, _on_timeout) end return test
错误信息
运行后触发如下错误:
E 0:00:00:894 connect: Cannot connect to 'timeout': the provided callable is null. <Erreur C++> Condition "p_callable.is_null()" is true. Returning: ERR_INVALID_PARAMETER core/object/object.cpp:1410 @ connect()
解决方案
错误原因是_on_timeout是_ready函数内的局部函数,无法通过self对象关联为有效Callable。以下是几种正确的实现方式:
方式1:将回调定义为脚本对象的成员方法
把_on_timeout定义为test表的成员函数,通过方法名连接信号:
local test = { extends = Node2D, } function test:_ready() local timer = self:get_tree():create_timer(2) -- 连接到对象的_on_timeout成员方法 timer:connect("timeout", self, "_on_timeout") end function test:_on_timeout() print("timeout end") end return test
方式2:使用局部函数直接连接
如果回调仅在_ready内使用,可直接传递局部函数作为Callable:
local test = { extends = Node2D, } function test:_ready() local function _on_timeout() print("timeout end") end local timer = self:get_tree():create_timer(2) -- 直接传递局部函数 timer:connect("timeout", _on_timeout) end return test
方式3:使用匿名函数简化代码
直接在connect中定义匿名函数作为回调:
local test = { extends = Node2D, } function test:_ready() local timer = self:get_tree():create_timer(2) timer:connect("timeout", function() print("timeout end") end) end return test
关键说明
在Lua GDExtension中,connect方法支持两种Callable格式:
- 格式1:
对象:connect("信号名", 目标对象, "方法名"):要求方法是目标对象的成员函数 - 格式2:
对象:connect("信号名", Lua函数):直接传递Lua函数,无需关联对象
原代码错误在于混用了两种格式,将局部函数作为方法名字符串的参数传递,导致无法找到有效Callable。
内容的提问来源于stack exchange,提问作者Brandonn
相关产品推荐
相关产品推荐

