How to stop Instantiating after a max amount of prefabs is created

I am working on a game where prefabs spawn a certain amount of times in a random
position, and after a certain number is created, it stops creating them. I have made a
script that says what I want, but doesn’t stop deleting the prefab after the max number is made.

var Prefab : GameObject;
var PrefabLimit : int = 5; // Max amount of Prefabs
var PrefabCount : int; // Number of Prefabs in the game at a time
private var position: Vector3 = Vector3(Random.Range(-10.0, 10.0), 0, Random.Range(-10.0, 10.0));
// The position of where the Prefabs will spawn
    function Update () {
    	if (PrefabCount < PrefabLimit){
    	// If the number of Prefabs in the game is less than the max number of Prefabs
    		Invoke("PrefabSpawn", 2, 0.3);
    		// Repeat the function PrefabSpawn()
    	}
    	else
    	{
    		CancelInvoke("PrefabSpawn");
    		// Stop the function PrefabSpawn()
    	}
    }
    
function PrefabSpawn() {
	Instantiate(Prefab, position, Quaternion.identity);
	// Create the prefab using a random position
	PrefabCount++;
	// Raise the number of prefabs in the game in variable PrefabCount
}

This is a newbie script, I know, but I don’t know how to make a script that will work the way I want it to. I appreciate any feedback.

its so simple …

you can check this for more details

you can use a function named “CancelInvoke()”

for exemple : if (number_of_object_spouned >30)
{
CancelInvoke()
}

i hope this helps you ^ ^

OK, I had to read that script a couple of times, I may be wrong, but here’s what I THINK happens:

In Update, you start a LOT of Invoke’s. And only after some time you actually get to the Cancel.

Problem is: You are using Invoke inside Update.

Instead: Use InvokeRepeating - and Call it From Start

I hope that gives you enough to go on :wink: