Godot 4.0.2函数执行后条件重复检查引发空对象错误
Godot 4.0.2 按钮销毁后触发空对象错误的解决办法
问题还原
代码逻辑是在_process中检查自定义对象参数与按钮文本是否匹配,匹配后关闭_process,调用函数销毁该按钮,但特定场景下执行完销毁函数后会再次进入条件检查,此时按钮已被销毁,触发"Nil对象无text属性"错误,且已排除信号干扰。
if CustomObject.string_parameter == ButtonReference.text: set_process(false) my_function(Node, CustomObject)
问题根源
set_process(false)会阻止后续帧的_process调用,但当前帧的_process执行流程可能未完全结束;或者按钮通过queue_free()延迟销毁的特性,导致同一帧内按钮对象状态变化后,代码仍尝试访问其属性。
可行解决方案
1. 提前缓存按钮文本
在条件判断前先将按钮文本存入变量,避免后续访问已销毁对象的属性:
var button_text := ButtonReference.text if ButtonReference else "" if CustomObject.string_parameter == button_text: set_process(false) my_function(Node, CustomObject)
2. 销毁时清空按钮引用
在my_function中销毁按钮的同时,将ButtonReference设为null,彻底切断对已销毁对象的引用:
func my_function(node: Node, custom_obj: CustomObject): # 执行其他操作 if ButtonReference: ButtonReference.queue_free() ButtonReference = null # 清空引用,避免后续访问
3. 延迟执行销毁函数
用call_deferred让my_function延迟到当前帧_process结束后执行,确保set_process(false)已生效,不会在同一帧内重复触发条件检查:
if CustomObject.string_parameter == ButtonReference.text: set_process(false) call_deferred("my_function", Node, CustomObject)
内容的提问来源于stack exchange,提问作者DotFX
相关产品推荐
相关产品推荐

