Godot 4:玩家进入Area2D时修改UI场景Label文本异常问题
解决方案:Godot 4场景切换时传递UI参数的问题
问题根源
- 场景实例复用错误:你在
EntryPoint.gd中实例化了location对象并设置了名称,但实际切换场景用的是targetLocation这个原始PackedScene,相当于重新实例化了一个全新的场景,之前的设置完全无效。 - 节点就绪时机不匹配:即使传递了正确的实例,在调用
setLocationName时,节点还未加入场景树,@onready标记的nameLabel等变量尚未初始化,直接访问会触发空引用异常。
修改代码
1. 修正EntryPoint.gd(传递已配置的实例)
extends Area2D @export var targetLocation : PackedScene @export var locationName: String func _on_body_entered(body): # 实例化目标场景并保存到变量 var location_instance = targetLocation.instantiate() # 给实例设置名称 location_instance.setLocationName(locationName) # 使用实例切换场景,而非原始PackedScene get_tree().change_scene_to_node(location_instance)
2. 优化Location.gd(处理节点就绪状态)
extends Node @onready var itemList = $VBoxContainer/HBoxContainer/VBoxContainer/ItemList @onready var nameLabel = $VBoxContainer/HBoxContainer/VBoxContainer/LocationName @onready var image = $VBoxContainer/HBoxContainer/Image var localName: String = "test" func setLocationName(newName: String): self.localName = newName print(self.localName) # 节点就绪后直接更新UI,未就绪则等待_ready触发更新 if is_node_ready(): nameLabel.text = self.localName func setLocationImage(newImage: Image): # 同样判断节点状态,避免空引用 if is_node_ready(): image.texture = newImage func _ready(): print("ready") update() # 生成角色等其他逻辑保留... func update(): print("update") nameLabel.text = self.localName print(self.localName)
额外说明
change_scene_to_node会直接将已实例化的节点作为新场景加载,保留你之前对实例的所有配置。is_node_ready()用于判断节点是否已加入场景树,确保@onready变量初始化后再操作UI元素,彻底避免空引用。
内容的提问来源于stack exchange,提问作者Kiowe Smith
相关产品推荐
相关产品推荐

