How to stop Enemys spawning every frame from every spawn point?
i made a spawner script where i put enemy spawners around the scene to spawn enemys at random intervals and positions what ends up happening is that it spawns an enemy every frame from every spawn point and i dont know how to fix it (it doesnt show errors) can someone help? this is the script in C#
void Start()
{
timeBtwSpawns = startTimeBtwSpawns;
}
void Update()
{
if (timeBtwSpawns <= 0)
{
int randPos = Random.Range(0, spawnSpots.Length - 1);
Instantiate(enemy, spawnSpots[randPos].position, Quaternion.identity);
}
else
{
timeBtwSpawns -= Time.deltaTime;
}
}
if (timeBtwSpawns <= 0)
{
int randPos = Random.Range(0, spawnSpots.Length - 1);
Instantiate(enemy, spawnSpots[randPos].position, Quaternion.identity);
timeBtwSpawns = startTimeBtwSpawns;
}
And make sure the value of startTimeBtwSpawns is greater than 0.
Answer by f03n1x · Feb 08, 2019 at 04:14 PM
Normally what I'd do is setup something like this:
float timeBtwSpawns = 5.0f; //let's test every five seconds
float currentTimeBtwSpawns;
//Now inside the Update method what you should be doing is
void Update ()
{
currentTimeBtwSpawns += Time.deltaTime;
if (currentTimeBtwSpawns > timeBtwSpawns)
{
//Do stuff to spawn in enemies here
//Reset currentTimeBtwSpawns
currentTimeBtwSpawns = 0.0f;
}
}
I think what is happening is that you need a constant value that you want to check something against (check that the current time is greater than the time to spawn) and since you are not resetting this value it might be constantly meeting the condition to spawn, what you can do to check this though is just do a simple debug log printout to see what the value is currently at:
(Debug.Log("TimeBtwSpawns: "+timeBtwSpawns)); //put this at the top of the update method and it should tell you where it's at
Your answer
Follow this Question
Related Questions
How to stick to an object when a button is pressed Unity 2d 0 Answers
Unity 2d Collision Glitch Help 0 Answers
UI inputfield not shows mobile keyboard on click 0 Answers
How do i fix my problem with minimizing/maximizing and just opening unity editor windows? 0 Answers
Slider.value doesn't show the value in real-time but after the execution of the script 1 Answer