calling function once?

Under function update its checking to see If the score has changed, and if it has then it will call/trigger/activate the “Spawn” function and Instantiate an object. The problem is that it Instantiate hundreds of objects, its calling it every frame. how can I get to only call spawn once.

#pragma strict

var Score : float = 5f;


var NPC : Transform;
var NPCPoint1 : Transform;

function Update(){
	if  (Score == 5){
		Spawn();
	}
}

function Spawn(){
		Instantiate(NPC, NPCPoint1.position, NPCPoint1.rotation);
}

You may add a boolean variable to check if the function was called, like this:

 #pragma strict
 
 var Score : float = 5f;
 
 var NPC : Transform;
 var NPCPoint1 : Transform;

 // This is the added boolean variable.
 // It initially contains false because Spawn() is not called yet
 var spawned : boolean = false;

 function Update(){
     // This condition does not get true value if spawned is true
     if  (Score == 5 && !spawned){
         Spawn();
         //Now spawned get true value because Spawn() is called
         spawned = true;
     }
 }

 function Spawn(){
 	 Instantiate(NPC, NPCPoint1.position, NPCPoint1.rotation);
 }

Just throw a trigger in there to turn off spawning once you’ve spawned one thing:

var hasSpawned : bool = false;
function Update(){
    if  (!hasSpawned && Score == 5){
        Spawn();
        hasSpawned = true;
    }
}

Instead of using booleans, you could implement two scores, with one that “catches up”.

var score = 5;
var oldScore = 4;

function Update() {
    if(score != oldScore)
        {
        Spawn();
        oldScore = score;
        }
}

This way he could reset the trigger without relying on Spawn() triggering. :wink: