invalid operands 'nil' and 'int' in operator '+'

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

why does my script think that global.openlevs is null?

here is the global script if it helps:

by the way when i remove the save and load functions the script works for some reason

thanks.

Please copy and paste your code here.

Ertain | 2022-01-10 20:26

levelmenu.gd:

onready var global = $“/root/Global”
onready var openlevss = global.openlevs

func _ready() → void:
for i in range($levels.get_child_count()):
Global.levels.append(i+1)

for level in $levels.get_children():
	if str2var(level.name) in range(openlevss+1):
		level.disabled = false
	else:
		level.disabled = true

Global.gd:

var openlevs = 1

var levels =

var file_name = “user://saved.save”

func save_game():
var save_file = File.new()
save_file.open(file_name, File.WRITE)
save_file.store_var(openlevs)
save_file.close()

func load_game():
var save_file = File.new()
if save_file.file_exists(file_name):
save_file.open(file_name,File.READ)
var openlevs = save_file.get_var()
save_file.close()
return openlevs

func _ready():
openlevs = load_game()

kitsune | 2022-01-11 12:14

:bust_in_silhouette: Reply From: ponponyaya

I found that your save data type is not correct, so after function ready() runs, you will get a null.

Try this following

var openlevs = 1
var fileName = "res://save.save"

func _ready():
	if loadFile(): # check isn't null
		openlevs = loadFile()

func save():
	var saveFile = File.new()
	saveFile.open(fileName, File.WRITE)
	var saveDatas = {"openlevs": openlevs} # note: the data type
	saveFile.store_var(saveDatas)
	saveFile.close()

func loadFile():
	var loadFile = File.new()
	if loadFile.file_exists(fileName):
		loadFile.open(fileName, File.READ)
		var loadDatas = loadFile.get_var()
		loadFile.close()
		return loadDatas["openlevs"] # return an int in this case

This example in my test is ok, hope this help.

sorry it did not work
it still thinks the value is null

kitsune | 2022-01-11 12:11

Have you set the “Global.gd” as Singleton (AutoLoad)?

ponponyaya | 2022-01-11 12:18

yes i did

kitsune | 2022-01-11 12:24

I found a new answer above maybe you can try this.

ponponyaya | 2022-01-11 14:24

Thank you very much it finally worked

kitsune | 2022-01-11 14:55