How to get a specific node from an Array without name or reference?

Godot Version

4.6.1

Question

From what I’m seeing, the functions for getting something from an array require a reference to the specific node, but what if you want to find a specific node without the specific name or reference?

I have a scene with a bunch of instantiated cubes in it which are all put in an array at ready. Each cube has a script on it that lets you hover over it with your mouse and click on it to select it.
(Shown below, brick in white is selected)


Additionally, more cubes will be added over time as they’re instantiated and added to the array.

In case it helps, the code for selecting the cube is below. Once the player left clicks on the cube it gets selected and the outline is applied.

func _on_input_event(camera: Node, event: InputEvent, event_position: Vector3, normal: Vector3, shape_idx: int) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
		if selected == false and Global.bricks_selected < Global.brick_select_limit:
			brick_mesh.material_overlay.set("shader_parameter/color", Color8(0, 0, 0))
			selected = true
			Global.bricks_selected += 1

How would I go about finding and selecting the specific cube in the array when it’s selected? Like when it’s clicked, it finds that cube in the array so that I can then run code that effects that cube.

Sorry if my explanation isn’t great but I hope I was able to get my question across, thanks in advance!

You need to have some kind of reference to the specific Node. How else would you know which specific Node you want to retrieve?

You need a reference, and then once you have that reference, I don’t really understand why you’d need to retrieve the Node from the Array if you already have the reference.
Your _on_input_event() callback already creates that reference for you, because it is triggered on the Node that you want to have a reference for, so self within that script is the reference you need. Do whatever you want with that Node then.

1 Like

Why not update the location of the cube rather than try and recreate it each time?

1 Like

You can step through the array and test for a function or class using a for loop. If it’s a huge array it would be a problem but if it’s 10 or 20 objects, it would be fast enough.

1 Like