0 votes

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 playersdict and shows both players in there. But when the scene changes to GameWindow and I print out players (I have "onready var players = getnode("/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??

in Engine by (39 points)

1 Answer

+1 vote

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.

by (317 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.