Access dictionnary value using node name

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

Hey, I’m trying to access sub-values in my dictionnaries using the name of the node trying to access those said values.

I’m storing a name on a Singleton when pressing a button like so :

func _on_Confirm_pressed():
GameData.characters["Player"]["Character_name"] = Character_name

Dictionnary looks like that :

var characters = {
"Player": {
	"Character_name": "",
	"Username": "",
}

}

And when the node is intanced, I try to access it like so :

func _ready():
print(GameData.characters[str(self.name)]["Character_name"])

I tried both with and without the str(), but I can’t seem to make this work.

How can I access my dictionnary using the name of the node calling it ?

:bust_in_silhouette: Reply From: PrecisionRender

You need to add a key to your dictionary with the name of your player before accessing it. Also, using str() is unneeded since Node.name returns a string by default.

func _ready():
    GameData.characters[self.name] = {
        "Character_name": "",
        "Username": "" }
    print(GameData.characters[self.name]["Character_name"]) 

So, doing this, I’ll create an entirely new dictionnary within the singleton ?

That may cause an issue since I need to change the character name before instancing it (using a lobby, the player will use buttons to choose a character, and then it will get launched in the game)

Or am I not understanding something about dictionnaries ?

Rensae | 2021-09-28 15:49

You will create a new dictionary, but it will go inside the GameData.characters dictionary, not directly inside the singleton. I’m sorry if I don’t fully understand your question. Do you need the GameData.characters dictionary to only have the “Player” key in it?

PrecisionRender | 2021-09-28 16:52

Well, I’m trying to make a multiplayer game

So, I’m using a Lobby to let every player choose their characters.

I was thinking about using a dictionnary to store the name of the character each player used, and use that name to instance the correct character, with the correct sheet / animation and correct skills

So, I’ll need the Gamedata.characters dictionnary to store data for “Player”, but also “Player2”, “Player3” and “Player4”

I have a lot more questions than this one, but it’s not like I can use anything but here to ask about all the things I don’t really understand.

I’m still a newbie at game development haha.

Rensae | 2021-09-28 16:56