Godot Version
4.2.1
Question
Lets say I write strategy game. I instantiate building which immediately instantiates unit:
extends Node3D
class_name Game
var building_scene: PackedScene = preload("res://buildings/building.tscn")
func _ready() -> void:
var building: Building = building_scene.instantiate()
get_tree().get_root().get_node('./Game/Map').add_child(building)
unit.global_position = Vector3(123, 56, 32)
extends Node3D
class_name Building
var unit_scene: PackedScene = preload("res://units/unit.tscn")
func _ready() -> void:
var unit: Unit = unit_scene.instantiate()
get_tree().get_root().get_node('./Game/Map').add_child(unit)
unit.global_position = global_position + Vector3(0, 1, 0) # global_position is equal Vector3(0, 0, 0)
Problem is global_position in a last line of Building script. It’s equal zero because _ready() function is called after add_child and before setting global_position.
Solution is to change order in Game script, firstly set global_position and then add node to tree:
extends Node3D
class_name Game
var building_scene: PackedScene = preload("res://buildings/building.tscn")
func _ready() -> void:
var building: Building = building_scene.instantiate()
building.global_position = Vector3(123, 56, 32) # it works but throws an error
get_tree().get_root().get_node('./Game/Map').add_child(building)
This change works as expected but godot logs error:
Condition “!is_inside_tree()” is true. Returning: Transform3D()
Is there any elegant solution to set global_position and avoid this error?