Accessing an object from a dictionary with a string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Luka38
:warning: Old Version Published before Godot 3 was released.

Is there a way to get an object from another node’s dictionary by using a string?
For example, I have a dictionary named levelList with a bunch of objects all named level_000, level_001, level_002…
Now I want to access, let’s say, levelList.level_000 in another node.

var levelSpace
var levelList
var level
export var levelName = "" # where I give the name (like "level_000")

func _ready():
   levelSpace = get_parent().get_parent().get_parent().get_parent()

   levelList = levelSpace.levelList
   print(levelList.level_000) # this works

   level = levelList.level_000 
   print(level) # this doesn't work

And levelList.get(level_000) also doesn’t work.
Thanks for the help in advance

:bust_in_silhouette: Reply From: thepaperprojects

I would create a public api from the levelSpace

[in levelSpace script]

func get_level_list(key):
    return self.levelList[key]

[usage]

var levelSpace

func _ready():

    levelSpace = get_parent().get_parent().get_parent().get_parent()

    print( levelSpace.get_level_list("level_001") )
:bust_in_silhouette: Reply From: avencherus

You can access the key also with braces. So if you want to pass it a string or variable, the notation would look like this.

levelSpace.levelList[levelName]

Thanks dude! I found a more convoluted way of making it work, but this is so much better :smiley:

Luka38 | 2017-12-13 09:24