How to access array made in Singleton Autoload

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

Currently I want to import all my image files at runtime, which i’ve successfully managed to store in an array.

However, I cannot seem to access ANY variable found in a singleton. I just get an error.

For example, I have a singleton, here is the code for it:

extends Node2D

func _ready():
	var pics = []
	var a = 1
	var path = "path/to/imagesFolder"
	var dir =
	while true:
		var file_name = dir.get_next()
		if file_name == "":
			#break the while loop when get_next() returns ""
		elif !file_name.begins_with(".") and !file_name.ends_with(".import"):
			#if !file_name.ends_with(".import"):
			pics.append(load(path + "/" + file_name))

In my Picture_display node I have the following code:

extends Sprite

func _ready():

When I run this scene I get the error:
"Invalid get index “a”(on base: ‘Node2D (’).

This is really confusing me as I am following at least what I think the documentation is telling me. Also the Enable next to the singleton is checked. I even added the Picture_import scene (which has the pics_array node in it) but i’m still not getting any variable access.

I should add that i’ve already searched online but I havn’t found the answer i’m looking for yet.

:bust_in_silhouette: Reply From: jgodfrey

So, a number of problems based on the code you posted…

First, the a variable in the script has nothing to do with the pics array. That is, they’re completely independent variables. I’m not sure why you’d expect to be able to access pics.a.

Second, the pics variable and the a variable are local to the _ready function in the global script. So, even if you were using them correctly, you couldn’t access them from somewhere else.

Based on what you seem to be trying to do, you probably want something like:

In the singleton (at the top, outside of any function):

var pics = {"a": 1, "b": 2}

That’s a Dictionary, which will let you access the value (1) by its key (a) using:


The second paragraph about local variables is exactly what I needed to know.

With regards to the accessing of pics_array.a if there is something I don’t understand I tend to work with basic testing variables that arn’t related to anything else in the code and then work from whatever success I can find. I know its basic but i’m still a novice and i’m not sure of a better way of testing things out just yet (I havn’t got round to learning how to use most debuggers).

Thank you so much for the detailed and quick response, just managed to finish my first project in Godot based off your answer.

Rickers | 2020-02-25 18:21