Global variables not updating for some reason

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

I’m trying to add another player into a dictionary. I’ve got GlobalVars.gd as a singleton and it has

extends Node

func save_players():
	var players_dict = {
		"player1":{
			"username":"user1",
			"password":"password",
			"hand_cash":0,
			"bank_number":0,
			"bank_pass":"",
			"real_ip":"127.0.0.1",
			"external_ip":"",
			"network":"network1"
		}
	}
	return players_dict

And in RegisterWindow.gd I’m trying to add a player2 into the dictionary.

extends Node

onready var players = get_node("/root/GlobalVars").save_players()

players["player2" = {
"username":"jack",
"password":"jackiscool",
"hand_cash":0,
"bank_number":0,
"bank_pass":"",
"real_ip":"127.0.0.1",
"external_ip":"",
"network":null
}
print(players)
get_tree().change_scene("res://GameWindow.tscn")

When I print players after I add player2, it prints out players_dict and shows both players in there. But when the scene changes to GameWindow and I print out players (I have “onready var players = get_node(”/root/GlobalVars").save_players()" at the top of GameWindow.gd as well) then it shows that only the original player is there and no new player is added. Somehow it deleted player2 from the dictionary??

:bust_in_silhouette: Reply From: pgregory

I suspect the problem is that your globals don’t define and hold the players_dict as a global variable, but rather as a function local variable. That is, every time the function save_players() is called, it will create a new players_dict and return it.

Better to make the players_dict a member variable on the globals singleton.

extends Node

var players_dict = {}

func save_players():
    players_dict = {
        "player1":{
            "username":"user1",
            "password":"password",
            "hand_cash":0,
            "bank_number":0,
            "bank_pass":"",
            "real_ip":"127.0.0.1",
            "external_ip":"",
            "network":"network1"
        }
    }
    return players_dict

However, you do still need to be mindful of the fact that each time save_players() is called, it will still reset the global players_dictto a single value, so be careful when it is called.