Topic was automatically imported from the old Question2Answer platform.
Asked By
zendorf
Old Version
Published before Godot 3 was released.
If I am instancing various enemies into a scene and they are being destroyed continually, I need to check the count of each type at various times.
Do I need to do this manually via variables or an array, or is there a function to get a current count of how many are in the current scene? get_instance_count() is only for the multimesh…is there something like this for normal instanced objects?
I realise that this may be tricky as each instance has a unique name. Since I am tagging them all with a set_meta (“type” , “enemy”) it would be great to be able to get a count via metatags. Possible?
I have had a bit of a play, and as suspected it is WAY faster doing it manually. I have a few hundred instanced objects and it surprisingly slow to get an array of all children and traverse through it. So much so, that there is a distinct pause in the runtime when it happens.
Having said that, it could be useful if my instanced object where made children of named null groups rather than direct children of the scene root. They would in essence be a hierarchical group…anyway an idea to play with on another day
For those that might be interested, here is a basic code example of what alket suggested. This will count the number of instances I have tagged with the “enemy” type metatag:
var enemy_count = 0
var children = get_parent().get_children()
for i in children:
if i.get_meta("type") == "enemy":
enemy_count += 1
print("enemy count: " + str(enemy_count))
It is a very old post, but just to help others with the same doubt, it is always a good practice to use the available functions. In this case, you can use the function get_children() to get all the nodes inside a parent or specifically to get only the number of nodes attached you can use get_children().size() and you receive an int value back.
Add each kind of enemy subscene to ‘ENEMIES’ group and just:
get_tree().get_nodes_in_group("ENEMIES").size();
Thanks, that is really nice and simple way of doing it! I have been creating so many metatags that I completely forgot about using groups.
zendorf | 2016-02-24 11:21
Yeah, it’s simple fast and flexible… and when it’s for scenes like ‘enemy’ it’s usually a ‘must have’ since it will be useful in other scenarios also (like propagating events).
kubecz3k | 2016-02-24 11:32
Is it possible to get an array or list of all nodes in the tree?