My Array outputs <Object#null>

Godot Version

Godot Engine v4.4.1.stable.steam.49a5bc7b6

Question

I am trying to make an array in a global script that has some 2D nodes, but when i try to print this array in another script it outputs <Object#null>. Can someone explain me whats happening?

My global script:

@onready var EnemyPostitions: Array = [$"Neo metal2/Neo Metal/Aim",$"Neo metal2/Neo Metal2/Aim",$"Neo metal2/Neo Metal3/Aim",$"Neo metal2/Neo Metal4/Aim"]

My other script:

extends CharacterBody2D

func _process(delta):
    print(Global.EnemyPostitions)

The array is initialized with the @onready attribute.
Is there any node on which the Global script is attached, so that the ready event can be triggered on it? If not, that’s the issue.

1 Like

The Globbal script is attached to the Eggfleet node

1 Like

Globals are instanced when the game runs, you’ve made a double, one global, and another in the scene. Check the “remote” tab in the scene tree when the game is running, you will see another “global” node beside the current scene with no children, that’s the Global.

2 Likes

Also the dollar syntax doesn’t make sense on a global node. It’s a syntactic sugar for the get_node function. It searches in the node children, but globals usually don’t have any!

My advice is have the children add themselves to the global’s array variable. Or use groups.

2 Likes

It worked! thank you

Worth noting that globals can have children if you add the scene .tscn as the global, instead of the script .gd, and/or your script could add children dynamically on _ready or otherwise.

Groups seem like the best option here for sure.

2 Likes

I find that the best use of Globals is as an Autoload, but that’s me. That way it has no dependency and can be used globally, as its name suggests.

Anyway, that’s my 2c.

Didn’t know that you can have .tscn files as globals! I always just put a .gd script in there. Thanks for that tip!

1 Like

Accessing nodes by pathing from an autoload is not a great idea, as autoloads persist between scenes. I’d reccmmend, if you really want global access to a few nodes, that you instantiate this array empty then add those node objects to it at runtime from their local instances, then clear it between scene changes. If you insist on pathing from an autoload, the path should begin with the root node as well. eg: Eggfleet/Neometal2/etc....

Off the global idea, but it rather looks like you just need access to these nodes at the Eggfleet script rather than an autoload. In this case you can use unique names to access everything locally pretty seamlessly. Scene Unique Nodes — Godot Engine (stable) documentation in English

1 Like

I’ve seen someone, in a video, using their entire GUI in an autoload. There are worse ideas. :grinning: :man_shrugging:

Yes, you’re right. It will also make things really hard to maintain and adapt to other situations if the need arises.

1 Like