Script call to identify quantity of specific enemy in a troop

Hi everyone,

I need to run a condition to see how many enemies of a particular type are in the current battle troop. It's to be used inside a Yanfly action sequence. Any thoughts?

Thanks.
I'm assuming that by "type", you mean the ID number of the enemy (Bat is 1, Slime is 2, Orc is 3, etc.).

PHP:
var count = $gameTroop._enemies.filter(function(c) {return c._enemyId === X;}).length;

This snippet will store the number of enemies that are ID number X.
i.e.
If the troop contains 3 bats and 2 slimes, if you have X as 1 then the variable count will be 3.
Yeah, that's right. That's exactly what I wanted.

Thanks!

EDIT: @Aloe Guvner ... how would I turn this into an if statement?
You could write
Code:
if ($gameTroop._enemies.filter(function(c) {return c._enemyId === X;}).length === Y) {
    do something;
}
Where X is the ID number (Bat --> 1) and Y is the number of enemies needed for the statement to be true (3 Bats --> 3).
Or if you're doing it within an event conditional branch then just:
Code:
 $gameTroop._enemies.filter(function(c) {return c._enemyId === X;}).length === Y
Because the 'if' is applied already in the event conditional branch.

To explain what is going on here to anyone interested now or later:
  • $gameTroop is a global object (variable) that contains all of the information for the troop that is fighting.
  • $gameTroop._enemies is an array (a list of things) of the Game_Enemy objects in the troop. If fighting 3 bats and 2 slime then this is an array of 5 enemy objects.
  • Filter is a function that can be used on arrays. It looks through each element of an array and adds it to a new array if the element passes the test of the callback function.
  • The callback function in this case is anonymous and the test is whether the ._enemyId of the enemy object is a certain number.
  • After the filter is done, in our example we'll have an array of bat objects, because the slime objects got "filtered out", those didn't pass the test. I used quotes because the slime aren't actually removed from the $gameTroop._enemies, they are just not brought to this new (temporary) array.
  • To get the number of bats now we just take the length of the (temporary) bat array, if it was an array of 3 bat objects now it is just 3 (number).
@Aloe Guvner Cool man. What a great explanation. It's helped me understand what a lot of these scripting attributes actually do (variables, functions, arrays and filters). Thank you so much. I'm sure this will be of help to other rookies too.

Original thread: https://forums.rpgmakerweb.com/threads/script-call-to-identify-quantity-of-specific-enemy-in-a-troop.88715/