how to track the number of objects?

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

Hi, through which node and how can I track the number of objects in a certain zone? Objects are stored in the form of the variable “export (PackedScene) var”

:bust_in_silhouette: Reply From: njamster

The following is assuming a 2D-game, but should work similarly for 3D!

Create an Area2D-node and attach a CollisionShape2D to it. It’s shape and size will represent the zone you’re keeping track of. Make sure, each object you want to keep track of has a CollisionShape2D as well. Signals will be emitted when an object enters your zone, depending on the node-type you used for your objects:

  • area_entered, area_exited
  • if object is Area2D
  • body_entered, body_exited
  • if object is KinematicBody2D or RigidBody2D or StaticBody2D

So connect these signals on the “Zone”-Area2D to functions increasing or decreasing a counter variable to keep track of how many objects are currently inside the zone:

extends Area2D

var counter = 0

func _ready():
	connect("area_entered", self, "_on_Zone_area_entered")
	connect("area_exited", self, "_on_Zone_area_exited")
	connect("body_entered", self, "_on_Zone_body_entered")
	connect("body_exited", self, "_on_Zone_body_exited")

func _on_Zone_area_entered(area):
	counter += 1

func _on_Zone_area_exited(area):
	counter -= 1

func _on_Zone_body_entered(body):
	counter += 1

func _on_Zone_body_exited(body):
	counter -= 1

Please note that the entering/exiting body or area is based as a argument to the signal callbacks! This way it’s easy to restrict the counting even further, e.g:

func _on_Zone_body_entered(body):
	if body.is_in_group("ShouldCount"):
		counter += 1

Check the documentation, if you want to learn more about node groups.