How to put values inside a global array properly (mine always remains null)?

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

I have a setup like this:

a global singleton with code like this:

onready var dictionary0 = { "key1": "something", "key2": "something else"}
onready var dictionary1 = { "key1": "something", "key2": "something else"}
onready var array = [dictionary0, dictionary1]

func get_array():
   return array

I also tried this:

onready var dictionary0 = { "key1": "something", "key2": "something else"}
onready var dictionary1 = { "key1": "something", "key2": "something else"}
onready var array = []

func _ready():
  array.append(dictionary0)
  array.append(dictionary1)

func get_array():
   return array

But when I call get_array() from another function like this:

onready var singleton = get_node("/root/singleton)

func _ready():
var array = singleton.get_array()

it returns null. Same result with other values inside my array (I filled it with integers for testing purposes).
No matter, what I try, array remains null and I run out of ideas what I could possibly do to fix this.
I would appreciate any hints or alternative ways to solve this.

:bust_in_silhouette: Reply From: Reloecc

A) it’s not a singleton if it’s present in the scene tree. You are supposed to autoload singletons in project settings.

B) are you sure your singleton node is already ready when your “another function” is ready? As I don’t see a point of onready var(s) in singleton? Change it to just var.

I do autoload it in the project settings. Sorry, if i did not make this clear.

B) The file which calls the other function is a singleton too. Could this be the issue here?

Ciavarie | 2020-09-15 10:51

:bust_in_silhouette: Reply From: Zylann

The issue is you are making two singletons depend on each other. This is a bad design decision, because it’s harder to figure out which one will initialize first.

If you really want to do it this way, I suppose singletons will initialize and be ready in the order in which they appear in the singleton list, because “singletons” are in fact just nodes siblings of the current scene, under the root, which happen to be created in that order.

You can however make it order-independent by removing onready from your variable declarations. This will make the array initializer run when the singleton is created, before it is added to the tree and made ready.