Reference to multiple instantiated objects

Godot Version

Godot Engine v4.2.1.stable.official [b09f793f5]

Question

Im new to Godot and programming in general.
To keep it short.
I have a level-Scene, Enemy-Scene and Player-Scene

In all the scripts they reference to eachother in some way or another, see example:
@onready var enemy = $“…/Enemy”
@onready var enemy = $“…/Player”

And in the code use these variables to find out positions etc. like.
enemy.Global_Position etc.

All works fine until if i try to add another instance of the enemy-scene, in the node-tree it gets the name: Enemy2
Then my references cant find Enemy2, which is understandable
Deleting the first scene and re-naming Enemy2 to Enemy, then it works again.
So clearly hard-coded to only reference and look at: Enemy

Is there a way around this?
Am I using the reference wrong?(If i intend to have multiple copies of a node)

when you .instantiate() the enemy from a scene, or .duplicate() it straight from a node, you can “save” it to a variable by var new_enemy=
then you can append it to a list of enemy either in Dictionary or Array
get the reference by the array or dictionary you added in

other way, also include using add to group or have the enemy scene to be already in a group, then get the enemies list of node by var enemies=get_tree().get_nodes_in_group("enemy_group")

another way is to have the parent of the enemy nodes in, and just parent_node.get_children() to get all the enemy/ nodes inside the parent

2 Likes

ahh It works!
went with: enemies=get_tree().get_nodes_in_group(“enemy_group”)
since I already had a group for enemies.
For now I set it to only look at index 0.

seems like I got to change som logic and add some for-loops to go trough all the enemies. But atleast its not bound to the name of the Node.

Or is there another way to reference all the objects in the list other than to iterate through the list? an in-built method or something?

Thanks! :slight_smile:

you mean like, a script broadcast, then anything that can hear and connected/subscribed to it will response to it?
or simply you just want to make all these “enemy_group” group’s nodes to do something in a call?
then here’s it, calling the enemy_group’s group nodes to move to player when this line of code is run :
get_tree().call_group("enemy_group", "move_to_player")
note that the enemy should have the function/method named move_to_player

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.