Stop Infinitely Spawning Object on Javascript
Hello, I've written a Javascript for spawning an object after a certain seconds.
The object is spawning fine, but the problem is that it is infinitely spawning the object.
I want the spawning to stop after spawning one object.
Here is my script.
#pragma strict
var SpawnObject : GameObject;
var SpawnPoint : GameObject;
var SpawnCounter : int=0;
var SpawnCounterMax : int=0;
var myTimer: float=5.0;
function Update(){
if (myTimer >1){
myTimer -= Time.deltaTime;
}
{if (myTimer <=1)
{
Instantiate(this.SpawnObject, this.SpawnPoint.transform.position, this.SpawnPoint.transform.rotation);
this.SpawnCounter=0;
}
}
}
Thank you.
Answer by ElijahShadbolt · Oct 27, 2016 at 04:17 AM
When you instantiate the SpawnObject, I assume you would want to add 1 to the SpawnCounter. Every time you spawn an object, you could reset the timer to start again from 5 seconds. If you want to spawn as many objects as SpawnCounterMax, you could only execute the timer update if SpawnCounter < SpawnCounterMax.
#pragma strict
var SpawnObject : GameObject;
var SpawnPoint : GameObject;
var SpawnCounter : int=0;
var SpawnCounterMax : int=1;
var spawnTime : float=5.0;
private var myTimer : float;
function Awake(){
myTimer = spawnTime;
}
function Update(){
if (SpawnCounter < SpawnCounterMax)
{
if (myTimer >1){
myTimer -= Time.deltaTime;
}
else if (myTimer <=1)
{
Instantiate(SpawnObject, SpawnPoint.transform.position, SpawnPoint.transform.rotation);
SpawnCounter++;
myTimer = spawnTime;
}
}
}
If you only want to spawn one object, set SpawnCounterMax to 1 and you're good to go.
Your answer
Follow this Question
Related Questions
Bacteria/Cell Growth 1 Answer
Var GameObject not considering Clones. 0 Answers
Problem with Random Spawning 1 Answer
how to spawn clones with animations 0 Answers