Counting method object "when created"

Godot Version

4.2.1

Question

I created an object that serves as my character’s shot. The character has a cooldown where if he has 3 shots or more created he cannot shoot.

I created a counter for the shots so I can know how many are on the screen but I have no idea how to count how many objects were created.

I’ve already tried using groups, and recently I used the function “_on_visible_on_screen_enabler_2d_screen_entered()” where when the function is executed it will add +1 to the counter, but the function is only executed ONCE when the object is created and then it doesn’t work.

In short, I wanted to find a way to be able to count the objects that are on the screen or that have been created.

how do you create the object? that’s where you add the counter variable at, and emit signal to any nodes who needs it

1 Like

Can you show how you used groups? that would be my go-to option.

1 Like

Returning here, something bizarre happened, the scene file for my bullet object got corrupted, I tried to recreate what I had done but without success. I just wanted to know a method for me to know how many bullet objects there are on the screen and so I could count them.

In the photo I tried to redo what I had done, but without success.

Why do you expect this to work in the first place? You literally don’t do anything but declaring a variable bullet_count, initializing it to zero and printing it every frame in every bullet instance, without ever changing its value.

If you want to count bullets, don’t do it from the bullet instance, but from the node that’s spawning them. Just increase a counter with every call to instantiate.

Now of course you also would need to decrease that counter again when a bullet despawns. Simply let each bullet emit a signal before it calls queue_free, connect to it and update the counter accordingly.

Alternatively, just add the bullet instance to a group, and then recount all active nodes in that group every time you actually require the count.

1 Like