Instancing a scene through a dictionary

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

Hello there. I am getting this error
Invalid call. Nonexistent function ‘instance’ in base ‘Nil’.
when I instance a scene from a dictionary as per the example below:

export(PackedScene) var houses
export(PackedScene) var farms
var buildings = {'House':houses,'Farm':farms}

func next_building(typ):
     print(build_offset[typ])#To check if typ is valid
     var b = buildings[typ].instance() #ERROR

next_building('Farm')

If instead of instancing from the dictionary I do it like this then there is no problem.

var b = farms.instance()#Works
:bust_in_silhouette: Reply From: whiteshampoo

I have 2 solutions for you:

1: use onready:

onready var buildings = {'House':houses, 'Farm':farms}

2: fill the Dictionary in _ready:

var buildings : Dictionary

func _ready():
	buildings["House"] = houses
	buildings["Farm"] = farms

You have to get sure, that houses and farms are “loaded”, before you assign them to something.