get_nodes_in_group adds a null value to the end of the for loop

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

I have the following code

When I show the nodes that are in the group, 2 appear
Because I only have 2 node in that group, and in my whole project

enter image description here

But when I use the loop to print the nodes
At the end of all I get a null
.

@onready var enemies = get_tree().get_nodes_in_group("enemy")

func _ready():
	
	print(enemies)
	print(print_enemies(enemies))
	pass

func print_enemies(enemies_groups):
	for enemy in enemies_groups :
		if enemy != null:
			print(enemy)

.
Here is the example of what I get

#all nodes in group enemy
[MyEnemy:<Sprite2D#25753027719>, MyEnemy3:<Sprite2D#25786582153>]
#loop
MyEnemy:<Sprite2D#25753027719>
MyEnemy3:<Sprite2D#25786582153>

Why does that null appear? How do I make it not appear?

:bust_in_silhouette: Reply From: spaceyjase

Your loop is printing correctly but the code is also printing the return value of the print_enemies function (which is null because it doesn’t return a value). If your test code is:

func _ready():
    print(enemies)
    print_enemies(enemies)

It’ll work.

It worked, thanks

zkmark | 2023-05-06 01:07