# How can determine the number of instances of an object in Game Maker?

I am making a small puzzle based game. I want the number of instances of an object to be equal to the ammo count plus 2.

Each time a new room is loaded, the main object's creation method with run this script:

var ammo = instance_count(jellyfish)+2;


Then each time a bullet is fired, I subtract one. When there is no ammo left, the player goes to the 'failure' room.

However, I get the error: Unknown function or script: instance_count.

I have see this script on Google, but am not sure if it has deprecated or not. Is there a way I can do this?

The function you want is instance_number(obj) (documentation found here).

This functions returns the number of instances of a object that exist in the current room.

if you used instance_count you could do

jellyfish.instance_count+2

• Can you edit your answer to include the documentation surrounding the instance_count property? I don't see it. – MichaelHouse Feb 20 '15 at 23:34
• instance_count returns the all the active instances in the room: instance_count – xpy Mar 15 '15 at 10:46

I think it is because there is no jellyfish instances in the failure room. What you can do (I don't think this works in gamemaker 8.1, you actually have to use the room number, which is an integer (1, 2, 3, etc.)), but assuming you are using gamemaker studio you should use this, where failureroom is the name of the failure room:

if room != failureroom
{var ammo = instance_count(jellyfish)+2}


In this script the curly brackets are not necessary, but if you have more lines of code in the test like maybe you set the health as well, you have to use it.

Example:

if room != failureroom
{var ammo = instance_count(jellyfish)+2
var health = instance_count(jellyfish)+2}


If you do:

if room != failureroom
var ammo = instance_count(jellyfish)+2
var health = instance_count(jellyfish)+2


It will always change the health, even if you're in the failure room, but it will only change the ammo if youre not in the failure room.

You should use instance_number(jellyfish) instead of instance_count. Instance_count are ALL objects and instance_number(obj) is the count of A SPECIFIED object.