Counting of items in a given scene

Godot Version 4.3

My Situation:

I have planned several levels each with a different amount of collectables. It is supposed to be mandatory to collect all of them to activate the exit and be able to leave the level.

My Goal:

To have the amount of collectables in a given scene be automatically counted and use that value in different places like the counter in the UI (n-amount found/[amount of collectables]) and in the code as a pre-requisite for the goal working.

My Idea:

I think one way would be to assign the collectables to a group and have all the items in a scene belonging to such group be counted. But that’s guess-work on my behalf. I really have no idea to approach this code-wise.

Your solution:

Do you think that’s a viable approach? Is there a command that does what I envision? Do you have a better approach for this case?

Thank you for your time and happy new year! :slight_smile:

Your idea is one totally viable way to do this. You can find all collectibles in the scene by calling SceneTree.get_nodes_in_group() function.

If the array is empty, you can run your “exit” code.

var collectibles: Array[Node] = get_tree().get_nodes_in_group("collectibles")
if collectibles.is_empty():
	# exit

I think that’s a perfectly viable way to count collectables in a scene. You could use SceneTree — Godot Engine (stable) documentation in English to count the nodes in that group.

Thanks for all your input and excuse the late reply. Three days after the last reply my computer exploded… But I also solved the problem via a global signal!