Hello.

I am making a program in which I need to store the data of the whereabout of a sprite in a global variable to load it whenever I need to. This applies for a KinematicBody2D in Godot 4
I made a global variable:

var last_position : Vector2

Then, I made the following function that, when interacted with an object, saves this last position

func _process(_delta):
     if can_interact == true:
          Global.last_position = position

The can_interact parameter was working properly, and a position was being saved. But then, when I reused the same value some time after in the following function:

func victory():
     Global.xp += 25
     get_tree.change_scene_to_file("res://thepathofthefile")
     position = Global.last_position

The character would not be on the same position it was before and instead be transported always to the same spot outside the world. Am I doing something wrong?

  • You are setting the position of the old scene. This has no effect since the scene is replaced at this point. Move the position assignment to the _ready function of the new scene.

You are setting the position of the old scene. This has no effect since the scene is replaced at this point. Move the position assignment to the _ready function of the new scene.