How to use global_position and avoid error "!is_inside_tree()" is true. Returning: Transform3D?

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?

You can’t use the global_position property of nodes that are not in the scene tree yet because they’re not in the game world, so to say, so they don’t have a global position.

You can use the transform.origin property instead for nodes that are outside of the tree.
building.transform.origin = Vector3(123, 56, 32)

It should become it’s global position once it enters the tree, pretty sure that’s what godot already does under the hood, that’s why it works.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.