Need help filling an array

Godot Version

4.2.1 Stable Mono

Question

Can anyone tell me why this isn’t working?
print(spawners) only printed 13 <Object#Null>

var spawners: Array = []
func _ready() -> void:
	for i in range(1, 14):
		var spawner = $"Spawner Nodes/Spawner{i}"
		spawners.append(spawner)
	print(spawners)

I’m trying to put all of these into an array.
#@onready var spawner_1: Node2D = $“Spawner Nodes/Spawner1”
#@onready var spawner_2: Node2D = $“Spawner Nodes/Spawner2”
#@onready var spawner_3: Node2D = $“Spawner Nodes/Spawner3”
#@onready var spawner_4: Node2D = $“Spawner Nodes/Spawner4”
and so on.

As far as I know, the second argument for range is exclusive, this means that this will only go up to 13.
A possible solution is to start from 0 instead of one, as in most programming languages you count from 0, not 1.

1 Like

To simplify it, instead of the Spawner being a simple Node2D you can create a custom class just for them that extends from Node2D, then you can get them as children of the scene regardless of the number of them.

class_name Spawner extends Node2D

## Your logic here...
## New approach
var spawners := []

func _ready():
  spawners = get_children().filter(func(node): return node is Spawner)
# or appending it as array instead of direct assignation (if you have other elements in the spawner array)
spawners.append_array(get_children().filter(func(node): return node is Spawner))

From here you can refactor, create more methods, move logic to the spawner, etc.

The easiest ways to get an array of nodes is to use Node.get_children() or SceneTree.get_nodes_in_group().

If the spawners are the only children of the Spawner Nodes node, you don’t even need to add them to a new array. You can instead access them like this:

@onready var spawners = $"Spawner Nodes"

func activate_spawner_or_something(spawner_idx: int):
    var selected_spawner = spawners.get_child(spawner_idx)