gameover script

I have an object in my game that instantiates an enemy every minute. this what i want. I am looking for a script that will count the amount of enemies in the game and let say there can only be 10 of them. So if there are 11 enemies then game-over, load game over screen. I am new at scripting so your assistance will be really helpful.

Thank you so much.


What you can do is to define an empty game-object called 'controller', and attach a script like this to it

gameOver : boolean = false;

function Update()
   if (enemyCount > 11)
     gameOver = true;


function OnGUI()
   if (gameOver) 
      GUI.Label(Rect(0,0, 100, 20), "Game Over!);


function enemySpawned()

Of course, this is just the concept, not a solution. What you need to do is each time an enemy is spawned, inform the controller to increase the count of enemy by 1. You can use send message


There are many ways to do this. Experiment! :D

Next, the gist is that every game update, the script will check if the game over condition is met. If so, a boolean is set. The OnGUI() will detect that the game is over, and renders the game over message. You will also want to pause the gameplay, plays game ending music and etc. You can either have other scripts check for the gameOver boolean (which will do for a beginner's project), or freeze the game just to show a game over dialog box, or even jump to new a scene.

Here's a slightly alternative solution. Make a new JS script on an empty GameObject and replace its contents with the code below:

var baddieLimit = 10;

private var baddies : BadGuy[];

function Update() {

function CheckGameOver() {
    baddies = FindObjectsOfType (BadGuy);
    // get a list of baddie objects

    if (baddies.length > baddieLimit) {
         // if there are more than baddie limit, go to Game Over scene

Note: "BadGuy" should be replaced with the name of your enemy script, and GameOver the name of the unity scene file that contains a Game Over screen. It's also good practice to put your enemy limit into a variable too, so you can tweak it at leisure

What this does is, each frame it counts all the game objects that have a bad guy script, and if it exceeds the baddie limit value then go to a game over scene (you can just as easily replace this bit with GUI text, as in the example above). It should be stated that this is not as efficient as the above script, in that it searches for objects every frame instead of checking a value that is incremented with each spawn, but it may be easier to set up at first.