Store_var() doesn't work?

Godot Version

4.2.1 stable

Question

I’m folowing this tutorial. And i followed the instructions completely but whenever i save the game crashes with the error: Attempt to call function ‘store_var’ in base ‘null instance’ on a null instance. And i can’t get it to work. The error is at the save function at the bottom line 70: file.store_var(player.gloabal_position). here is my full code if that helps:

extends Node
@onready var player = %player
@onready var overlay = $“…/player/neck/head/Camera3D/overlay”
@onready var popup = $“…/player/neck/head/Camera3D/pause_menu/esc/popup”
@onready var popup_title = $“…/player/neck/head/Camera3D/pause_menu/esc/popup/Panel/vbox/popup_title”
@onready var ok = $“…/player/neck/head/Camera3D/pause_menu/esc/popup/Panel/vbox/ok”
@onready var warning = $“…/player/neck/head/Camera3D/pause_menu/esc/popup/Panel/warning”

var warning_reset = false

Called when the node enters the scene tree for the first time.

func _ready():
pass

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _process(delta):
pass

func _on_quit_pressed():
if player.is_on_floor():
_save()
get_tree().quit()
else:
_show_popup(“Can’t save because you are in the air!
The game won’t save if you continue!”)
popup.show()
warning.show()
ok.hide()

func _on_ok_pressed():
popup.hide()

func _on_load_pressed():
_load()

func _on_save_pressed():
if player.is_on_floor():
_save()
else:
_show_popup(“Can’t save because you are in the air!”)
popup.show()
warning.hide()
ok.show()

func _show_popup(title):
popup_title.text = title
popup.position = overlay.get_local_mouse_position()
popup.show()

func _on_i_know_pressed():
if !warning_reset:
get_tree().quit()
else:
get_tree().reload_current_scene()
Engine.time_scale = 1

func _on_reset_pressed():
warning_reset = true
_show_popup(“this will delete all save files and reset the whole game!”)
popup.show()
warning.show()
ok.hide()

func _save():
print(“yes”)
var file = FileAccess.open(“res://savegame.data”,FileAccess.READ)
file.store_var(player.global_position)
file.close()

func _load():
pass

func _on_cancel_pressed():
popup.hide()

The error message means, that file doesn’t contain a valid reference.
So the line

var file = FileAccess.open("res://savegame.data",FileAccess.READ)

is not succesful.

You could check if file is valid and if not try FileAccess.get_open_error() in order to get more details about why it failed.

If you want to write to a file, it should be opened with the flag FileAccess.WRITE or FileAcecss.READ_WRITE. Another thing is that res:// is usually read-only. Try to save the game status to user:// instead.

1 Like

thanks a lot! very stupid i just had to type FileAcces.WRITE not READ.

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