Godot页面切换报错:引用不存在资源与循环资源包含问题
问题解决:Godot主菜单按钮返回后无响应及循环引用错误
错误原因分析
- 脚本路径错误:第一个错误提示
res://script/main_menu.gd不存在,说明场景绑定的脚本路径有误(大概率是文件夹名应为scripts而非script,或是文件名拼写错误)。 - 循环资源引用:主菜单脚本预加载排行榜场景,排行榜脚本又预加载主菜单场景,导致Godot加载时出现循环依赖,场景无法正确初始化,返回主菜单后按钮功能失效。
- 语法错误:排行榜脚本的
_ready函数缺少闭合括号,且代码缩进不规范,导致脚本无法正常执行。
修复步骤
1. 修正脚本路径
打开main_menu.tscn,选中根节点检查Script属性:
- 确认脚本路径为实际存放路径(例如
res://scripts/main_menu.gd),而非错误的res://script/main_menu.gd。
2. 解决循环引用
移除互相预加载对方场景的代码,改用change_scene_to_file直接通过路径切换场景,避免预加载导致的循环依赖。
3. 修正语法错误
补全排行榜脚本_ready函数的闭合括号,调整代码缩进。
修正后的代码
主菜单脚本(main_menu.gd)
class_name MainMenu extends Control @onready var play_button = $MarginContainer/HBoxContainer/VBoxContainer/Play_Buttom as Button @onready var exit_button = $MarginContainer/HBoxContainer/VBoxContainer/Exit_Button as Button @onready var leaderboar_button = $MarginContainer/HBoxContainer/VBoxContainer/Leaderboar_Button as Button @onready var start_level = preload("res://scenes/game.tscn") func _ready(): play_button.button_down.connect(on_play_pressed) exit_button.button_down.connect(on_exit_pressed) leaderboar_button.button_down.connect(on_leaderboard_pressed) func on_play_pressed() -> void: get_tree().change_scene_to_packed(start_level) func on_exit_pressed() -> void: get_tree().quit() func on_leaderboard_pressed() -> void: get_tree().change_scene_to_file("res://scenes/leader_board.tscn")
排行榜页面脚本(leader_board.gd)
extends Control @onready var exit_button = $MarginContainer/HBoxContainer/VBoxContainer/Exit_Button func _ready(): exit_button.button_down.connect(open_main_menu) func open_main_menu(): get_tree().change_scene_to_file("res://scenes/main_menu.tscn")
额外注意事项
- 检查按钮节点名称拼写:主菜单中
Play_Buttom疑似拼写错误(应为Play_Button),若节点实际名称为后者需修正路径,否则会因找不到节点导致信号连接失败。 - 确保所有场景、脚本的文件名及路径大小写统一,Godot对路径大小写敏感(跨平台开发需注意)。
内容的提问来源于stack exchange,提问作者Olli
相关产品推荐
相关产品推荐

