Godot Version
4.7.2 Stable
Question
I am working on a WorldItem scene which will be the physical representation of all my items (which can be picked up) in the 3D world. It is a RigidBody3D root node with a CollisionShape3D child.
WorldItem updates itself by instantiating an item_model scene which is the visual representation of the item, as well as assign a collision shape for physics. I am using the tool functionality so that I can update WorldItem in the editor for adding handcrafted items in the level (I just create a new Item instance in the inspector and assign an ItemData to it).
In the documentation, I read some warnings about using queue_free() in the editor code but I couldn’t find much information on how to safely remove nodes in the editor. What I have currently works, but I don’t know if its going to cause issues later on. Any insight would be greatly appreciated!
@tool
class_name WorldItem
extends RigidBody3D
@export var item: Item:
set(new_item):
if item != null:
item.changed.disconnect(_rebuild_scene)
item = new_item
if item != null:
item.changed.connect(_rebuild_scene)
if is_node_ready():
_rebuild_scene()
var item_model: Node3D
@onready var collision_shape: CollisionShape3D = $CollisionShape3D
func _ready() -> void:
_rebuild_scene()
func _rebuild_scene() -> void:
# Reset the scene.
collision_shape.shape = null
if item_model != null:
item_model.queue_free() # Is this safe?
item_model = null
if item == null or item.data == null:
return
# Rebuild scene with new item data.
collision_shape.shape = item.data.world_shape
var model_scene: PackedScene = item.data.model_scene
if model_scene != null:
item_model = model_scene.instantiate()
add_child(item_model)