Godot 4自定义Inventory相关类脚本存在无法修复的语法错误,求助
Godot 4自定义Inventory类语法错误修复
问题描述
本人编程能力尚浅,使用ChatGPT生成了Godot 3脚本,在将其适配为Godot 4版本时,已修复多数不兼容问题,但自定义InventorySlot与InventorySlotContainer类的脚本仍存在无法解决的语法错误。
问题代码片段
extends CharacterBody3D # Structure to represent an inventory slot class InventorySlot: var background: TextureRect var item_icon: TextureRect # Constructor for InventorySlot func _init(): background = TextureRect.new() item_icon = TextureRect.new() # Container for inventory slots class InventorySlotContainer(Node): var inventory_slots: Array[InventorySlot] # Constructor for InventorySlotContainer func _init(): inventory_slots = [] # Function to add an inventory slot func add_inventory_slot(): var slot = InventorySlot.new() inventory_slots.append(slot) add_child(slot.background) add_child(slot.item_icon) # Declare the inventory container var inventory_container: InventorySlotContainer @onready var inventory_slot_container = InventorySlotContainer.new() # Declare the inventory slots var inventory_slots: Array[InventorySlot]
报错信息
Line 14:Expected ":" after class declaration. Line 14:Unexpected "(" in class body. Line 15:Unexpected "Indent" in class body. Line 29:Expected end of file.
错误原因与修复方案
核心错误点
- 类继承语法错误:Godot 4中自定义类继承父类的语法为
class 类名: 父类,而非class 类名(父类),这是第14行报错的直接原因。 - 缩进一致性问题:自定义类内部的成员变量和函数需保持统一缩进,否则会触发语法解析错误。
修复后的完整代码
extends CharacterBody3D # Structure to represent an inventory slot class InventorySlot: var background: TextureRect var item_icon: TextureRect # Constructor for InventorySlot func _init(): background = TextureRect.new() item_icon = TextureRect.new() # Container for inventory slots class InventorySlotContainer: Node # 修正继承语法 var inventory_slots: Array[InventorySlot] # Constructor for InventorySlotContainer func _init(): inventory_slots = [] # Function to add an inventory slot func add_inventory_slot(): var slot = InventorySlot.new() inventory_slots.append(slot) add_child(slot.background) add_child(slot.item_icon) # Declare the inventory container var inventory_container: InventorySlotContainer @onready var inventory_slot_container = InventorySlotContainer.new() # Declare the inventory slots var inventory_slots: Array[InventorySlot]
额外说明
- 修复后需确保
TextureRect节点的尺寸、位置等属性正确设置,避免后续运行时出现UI显示异常。 - 若仍有运行时错误,可检查节点添加逻辑是否符合Godot 4的节点树管理规则。
内容的提问来源于stack exchange,提问作者UbuntuDude10012000
相关产品推荐
相关产品推荐

