Invalid get index 'health' (on base: 'Dictionary').

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hymaa013

i get this when i try to save the player health"this my first time with save options so it will be simple to fix i think but i can not fix it"
the saving code:

extends Node

const savefile = "user://savefile.save"
var gdata = {}

func save():
	var file =File.new()
	file.open(savefile,File.WRITE)
	file.store_var(gdata)
	file.close()

func load():
	var file =File.new()
	if not file.file_exists(savefile):
		gdata={
			"health": 100	
		}
	save()
	file.open(savefile,File.READ)
	gdata=file.get_var()
	file.close()

health saving method:

func _on_kill_body_entered(body):
	if body.name == "player":
		save1.health -= 25
		get_node("coll").disabled=true
		life = false
		vel.x =0
		anim.play("death")

Edited to fix forum code formatting…

jgodfrey | 2023-07-01 18:58

So, if the error is in the above code, it’s here:

save1.health -= 25

So, save1 is apparently a Dictionary (though, you don’t show where it’s created or initialized), but it does NOT contain a key named health

jgodfrey | 2023-07-01 19:03

So what shoul i do to fix it ?
I showed where it created by typing the following line in my code but sorry i did not type it here in my Q

var save1 = savegame.gdata

hymaa013 | 2023-07-01 19:26

savegame is the script file name

hymaa013 | 2023-07-01 19:27

:bust_in_silhouette: Reply From: tuon

You can initialize gdata with the health and other default data in it. That may solve the issue.

var gdata = {
     "health": 100
}

Also, is the load ever being called? Maybe set a breakpoint in it and step through the code as it runs. If the breakpoint is never hit, then the load method isn’t called. Also, what’s in the savefile.data file?? Is it there? What’s in it?