API: swaping JSON files out

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

I’m making a api and am using 2 separate json files to store dialogue for 2 characters
but i need a way to swap out the file paths under some if condition so i thought to use a singleton from a different script to check an (int) variable called page. but the path variable won’t store a file for some reason

 extends Node 
var data = {}
var path = ""

var lu = "res://Json_Files/Lu_dialog.json"
var ciel = "res://Json_Files/Ciel_dialog.json"

export (String, FILE) var json_file = null

func _ready():
	var jsonfile = File.new()
	jsonfile.open(path, File.READ)
	data = parse_json(jsonfile.get_as_text())

this one is a root script to hold my page variable

extends Node

var page = 0

func _ready():

this code will ask an if statement to check how many pages our the number of pages determine the file and the line of dialogue to print out

extends Node

var root = get_tree().get_root().get_node("/root/global")
onready var gm = get_node("GameManager")

func _ready():

	if root.page == 0:
		gm.path = gm.lu
:bust_in_silhouette: Reply From: Zylann

You loaded your JSON file in _ready(), which means it will load as soon as the game starts. Setting the path in your page will have no effect for two reasons:

  • The script that reads path to load the JSON file may have run before. _ready() is called from parents to chidren order, and singletons always run first. So setting path after it was used is usleess.

  • Because JSON loading is in _ready it will run only once, so setting path multiple times will not make the data update anyways.

You have to either reload data everytime you set path, or just load all of then once in a dictionary so you can access them anytime without spamming the filesystem.