1
\$\begingroup\$

I'm making a simple version of the game asteroids as I'm learning how to develop with Game Maker Studio. Currently, mostly everything works properly except that when the player destroys all of the asteroids, I need the game to exit.

I've tried add the following line of script to the step event for the asteroid, but it resulted in a runtime error:

if (!instance_exists(obj))
  game_end();

This is a pretty simple problem but I haven't been able to find the answer on Google. What code should I add to check for any instances of asteroids and then to end the game when there are none?

\$\endgroup\$

2 Answers 2

0
\$\begingroup\$

One idea is to keep an array that tracks all of your asteroids. Every time you create an asteroid, add it to the array, and every time an asteroid is destroyed, remove it from the array. You can then use this function to check how many asteroids currently exist. If the answer is 0, end the game.

Someone who knows the GML API better might have a better solution, but this should certainly work. This method has the added benefit that you can check the number of asteroids in existence at any time; you could have a counter on the corner of your screen that tells the user how they're doing.

\$\endgroup\$
3
  • \$\begingroup\$ Thanks for the response! Do you know where I could store this file (i.e. which event to add the script)? If it would be in the create event, would I just have code in the script to basically add the current instance to the array? I'm assuming then that the check for the array length would go in the step event for the asteroid? \$\endgroup\$ Commented Feb 10, 2016 at 22:36
  • \$\begingroup\$ It depends how you're creating the asteroids. If you have a "Controller" object that has a line of code to create an asteroid, I would add the asteroid to the array at that same spot. If the asteroids aren't created, but instead start off in the room, then I think your only option is to use the create event in the asteroid object. As for the check, I wouldn't put it in the asteroid's step event, because then you'd have every asteroid checking the same thing (inefficiency). I would put the check in the step event of an object that there's only one of, such as the player. \$\endgroup\$
    – Peter
    Commented Feb 10, 2016 at 22:42
  • \$\begingroup\$ This should not be the accepted answer. instance_count() does this in one line of code. \$\endgroup\$
    – user64742
    Commented Dec 28, 2018 at 7:18
2
\$\begingroup\$

You could simply do:

if instance_number(obj) == 0 {  
    game_end()  
}  

This code should be put in a step event.

instance_number(obj) gets the amount of the defined objects in the room.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .