How to stop spawn after a limit (int)

Help on this question would be greatly appreciated - I am wondering if it possible to limit the amount of balls that are spawned?

The code is below. Thanks in advance

var ball : GameObject;
var spawn_position;
var timer = 0.0;

function spawn_ball ()

{

spawn_position = Vector3 (-2.77,3.3,0);

var temp_spawn_ball = Instantiate (ball, spawn_position, Quaternion.identity);

}
function Start () {

}

function Update () {

timer += Time.deltaTime;

if(timer > 8)

{

spawn_ball();
timer = 0.0;

}

}

You need to create a variable to hold the total amount of spawned balls and a variable for the current amount of spawned balls. Also, use a variable in place of ‘8’ when checking the timer because you might change this down the line, and it is easier to do so at the top, in one spot than multiple areas of your script.

I wrapped everything inside a boolean check because when the max amount of GameObjects are met the timer will keep going and this probably eats up resources. So, by turning the boolean off when the spawned limit is met, the timer will cease.

public var ball : GameObject;// the GameObject representing 'ball' (to be spawned)
public var spawnPosition : Vector3;// the position of the spawned GameObject
public var spawnLimit : int;// the max amount of GameObjects that can be spawned
public var spawnCount : int;// the current amount of spawned GameObjects
public var spawn : boolean;// if the GameObjects are allowed to spawn
public var waitTime : float;// the amount of time (delay) to wait before re-spawning
public var timer : float = 0.0;// the current time in seconds

function Start ()
{
	
}

function Update ()
{
	// check if GameObjects (the ball) can be spawned
	if ( spawn )
	{
		timer += Time.deltaTime;
		
		// check if the timer has reached the wait time
		if ( timer > waitTime )
		{
			// check if the current spawn amount is below the limit
			if ( spawnCount < spawnLimit )
			{
				Spawn ();// spawn the GameObject
				timer = 0.0;// reset the timer
			}
			else
			{
				spawn = false;
				Debug.Log ( "Spawn Limit Has Been Reached!" );
			}
		}
	}
}

// spawn the GameObject
function Spawn ()
{
	spawnPosition = Vector3 ( -2.77, 3.3, 0 );// set the position for the spawned GameObject
	Instantiate ( ball, spawnPosition, Quaternion.identity );// clone/duplicate the given object
	spawnCount++;// add to the current amount of spawned GameObjects (in your case, the number of balls)
	Debug.Log ( "Spawned GameObject #" + spawnCount );
}

You will run into a problem with your script though. Whenever a GameObject (ball) is spawned, it will appear in the same spot because you’re explicitly setting its position. Unless the GameObject (ball) is moving before the next spawn, you should use a random position.