Limiting spawn number

I´m currently working on a Horrorgame were i want monsters to spawn wenn the player is inside certain collision fields, so monster randomly pop up when the player takes the wrong turn.
I have already set up the spawn script wit Java, but i want to set a limitation to the amount of monster, for example no more than 10 monster should be on the map, but i dont know how to set it up correctly.

#pragma strict

var Mobs =  0;
var Spawn = false;
var Mob : Rigidbody;

function Update () 
{
	if (Spawn == true)
	{
	var clone : Rigidbody;
	clone = Instantiate(Mob, transform.position, transform.rotation);	
	} 
}

function OnTriggerEnter (theCollider : Collider)
	{	
		if (theCollider.tag == "Player")
		{
			Spawn = true;
		}
	}

	
function OnTriggerExit (theCollider : Collider)
	{
		if (theCollider.tag == "Player")
		{
			Spawn = false;	 	
		}
	}

This shouldn’t really be done this way, you should have a class to represent your mobs, but anyway, a quick and dirty patch would be to just use a counter to limit the moms.

private var nCurrentMobs : int = 0;
var nMaxMobs : int = 10;

each time you instantiate a mob, you first check to make sure you’re below your max, and then increase the current number of mobs:

if (nCurrentMobs < nMaxMobs)
{
   nCurrentMobs++;
   // do your thing...
}

A better way is to use a function to do the swapping for you, and not putting it in Update, I don’t see any reason for that

function SpawnMob()
{
    // 1- do your checks
    // 2- instantiate
{

function OnTriggerEnter (theCollider : Collider) {
   if (theCollider.tag == "Player") {
     SpawnMob();
   }
}

If you want to maintain a reference to your Mobs upon instantiation, add them to a List - Here’s how. This is a lot better because if you don’t keep a reference to what you instantiate, you won’t be able to destroy your mob later when you’re done with it.

You already catch the spawned enemy, or at least the rigidbody. Create an array in the spawner and keep track of the number of spawned enemies that way, and clean it up as monsters are removed.

Before a spawn is called there are a few different method for search through all of the gameobjects and looking for tags, names, or attached scripts. Set up the search to find your monsters and you have your count.