Can't access file contents from singleton script.

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

The problem:
I autoload a script (globals.gd) to access global variables in my scenes. Inside this script I have a set of commands for opening a file (save.sav). However, accessing the file prints null, whereas doing the same thing from a scene returns the file contents:

extends Node

func _ready():
	file = File.new()
	if file.open("res://save.save", File.READ_WRITE) != 0:
    	print("Error opening file")
	else:
		print("opened file")
		
	var d = file.get_var()
	print(d) 

What am I missing?

:bust_in_silhouette: Reply From: wombatstampede

I can say for sure that opening a file read/write from res:// will fail on some platforms and installations.

Try: file.open("res://somefilename.txt, file.READ)
And save files only in user://

The reason: res:// is for program resources and is often located in locations where the operating system does not allow writing.

It is better to discover sooner than later that you should not write to res:// unless you code some plugin/addon which is used from within the godot IDE during development.

I can attest that godot allows writing to user:// also from singletons because I personally use functions in my global.gd to write savegames to user://.

Thanks wombatstampede - appreciate your time

marcorexo | 2019-03-30 15:51