Neitan
Neitan

Reputation: 1

Checkpoint does not load correctly in Godot 4

I am developing a 2D game in Godot 4, and I am trying to create a "save and load (checkpoint)" system. Each scene's name follows a pattern like "world_01", "world_02", etc. The character starts in the "world_01" scene, and upon reaching the end, advances to "world_02". The location where the player starts is the location of the checkpoint, meaning that after passing scene 01, closing the application, and returning, the player should start in scene 02 (world_02). The code is successfully saving the checkpoint/scene, and upon closing and reopening, it also seems to load the checkpoint/scene, but when starting the game, it does not open and returns the error:

Invalid get index ‘global_position’ (on base: ‘Nil’)

Message returned when saving:

Checkpoint saved: res://levels/world_02.tscn(331, 270)
--- Debugging process stopped ---

Message returned when closing and reopening the game:

Globals script ready
Checkpoint loaded: res://levels/world_02.tscn(331, 270)

Archives:

checkpoint.gd:

extends Area2D

var is_active = false

func _on_body_entered(body):
    if body.name == "player" and not is_active:
        activate_checkpoint()

func activate_checkpoint():
    Globals.current_checkpoint = self
    Globals.current_checkpoint_scene = get_tree().current_scene.scene_file_path
    is_active = true
    Globals.save_checkpoint()

globals.gd (global):

extends Node

var player = null
var current_checkpoint = null
var current_checkpoint_scene = ""
var checkpoint_save_path = "user://checkpoint.sav"

func _ready():
    print("Globals script ready")  # Adicione uma mensagem para depuração
    load_checkpoint_from_file()

func _exit_tree():
    print("Tree exiting, saving checkpoint")  # Adicione uma mensagem para depuração
    save_checkpoint()

func respawn_player():
    if current_checkpoint_position != null:
        player.position = current_checkpoint_position


func load_checkpoint():
    if load_checkpoint_from_file():
        return {
            "position": current_checkpoint.global_position,
            "scene": current_checkpoint_scene
        }
    else:
        return null

func save_checkpoint():
    if current_checkpoint != null:
        var file = FileAccess.open(checkpoint_save_path, FileAccess.WRITE)
        if file:
            file.store_pascal_string(current_checkpoint_scene)
            file.store_var(current_checkpoint.global_position)
            file.close()
            print("Checkpoint saved: ", current_checkpoint_scene, current_checkpoint.global_position)
        else:
            print("Error opening file for writing")
    else:
        print("No current checkpoint to save")

var current_checkpoint_position = null

func load_checkpoint_from_file() -> bool:
    if not FileAccess.file_exists(checkpoint_save_path):
        print("Checkpoint file does not exist")
        return false # file not found
    
    var file = FileAccess.open(checkpoint_save_path, FileAccess.READ)
    if file:
        current_checkpoint_scene = file.get_pascal_string()
        var pos := file.get_var() as Vector2
        file.close()
        
        current_checkpoint_position = pos
        print("Checkpoint loaded: ", current_checkpoint_scene, pos)
        return true # got all data!
    else:
        print("Error opening file for reading")
        return false # failure to load

title_screen.gd (main scene):

extends Control

func _ready():
    pass # Não é necessário implementar nada aqui

func _on_start_btn_pressed():
    var checkpoint_data = Globals.load_checkpoint()
    if checkpoint_data != null:
        Globals.player.position = checkpoint_data.position
        get_tree().change_scene_to_file(checkpoint_data.scene)
    else:
        get_tree().change_scene_to_file("res://levels/world_01.tscn")

func _on_new_btn_pressed():
    get_tree().change_scene_to_file("res://levels/world_01.tscn")

func _on_credits_btn_pressed():
    # Implemente conforme necessário
    pass

func _on_quit_btn_pressed():
    Globals.save_checkpoint()
    get_tree().quit()

world.gd (script base/general):

extends Node2D

@onready var player := $player as CharacterBody2D
@onready var player_scene = preload("res://levels/player.tscn")

@onready var camera := $camera as Camera2D
# Called when the node enters the scene tree for the first time.
func _ready():
    Globals.player = player
    Globals.player.follow_camera(camera)
    Globals.player.player_has_died.connect(reload_game)


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    pass

func reload_game():
    await get_tree().create_timer(1.0).timeout
    var player = player_scene.instantiate()
    add_child(player)
    Globals.player = player
    Globals.player.follow_camera(camera)
    Globals.player.player_has_died.connect(reload_game)
    Globals.respawn_player()
    #get_tree().reload_current_scene()

The player begins in the first scene and not in the second scene where the checkpoint is located. What could be the reason for this?

Upvotes: 0

Views: 31

Answers (1)

Bugfish
Bugfish

Reputation: 1729

As your error states: You try to get the global position of a variable that is nil.

Looking at your loading code I am pretty sure this is happening here:

func load_checkpoint():
    if load_checkpoint_from_file():
        return {
            "position": current_checkpoint.global_position, <--- here
            "scene": current_checkpoint_scene
        }
    else:
        return null

the reason is, that current_checkpoint never gets initiated, nor saved in your script. You load the position into a different variable:

func load_checkpoint_from_file() -> bool:
    if not FileAccess.file_exists(checkpoint_save_path):
        print("Checkpoint file does not exist")
        return false # file not found
    
    var file = FileAccess.open(checkpoint_save_path, FileAccess.READ)
    if file:
        current_checkpoint_scene = file.get_pascal_string()
        var pos := file.get_var() as Vector2
        file.close()
        
        current_checkpoint_position = pos <-- here

So just change current_checkpoint.global_position into current_checkpoint_position

Upvotes: 1

Related Questions