- Home /
Question by
kayo-chan · Oct 15, 2019 at 01:45 AM ·
spawning-enemies
How can I increase the rate of spawning with respect to scores gotten?
Here is my code, I tried doing the following but it doe not work.
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
public PlayerHealth playerHealth;
public GameObject enemy;
public float spawnTime =10f;
public Transform[] spawnPoints;
void Start()
{
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Update()
{
if (ScoreManager.score >= 100 & ScoreManager.score < 200)
InvokeRepeating("Spawn", 3, 7);
enabled = false;
if (ScoreManager.score >= 200 & ScoreManager.score < 300)
InvokeRepeating("Spawn", 3, 4);
enabled = false;
if (ScoreManager.score >= 300)
InvokeRepeating("Spawn", 1, 1);
enabled = false;
}
void Spawn ()
{
if(playerHealth.currentHealth <= 0f)
{
return;
}
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position,spawnPoints[spawnPointIndex].rotation);
}
}
Comment
Answer by GrayLightGames · Oct 15, 2019 at 04:16 AM
You may need to call CancelInvoke to stop the original InvokeRepeating, but I don't have much experience with InvokeRepeating. I believe the original InvokeRepeating will continue until you cancel it, so you'll have multiple InvokeRepeatings that overlap. If someone with more experience can confirm this, that would be great.
If that doesn't work, you could manage the countdown yourself instead of using InvokeRepeating and you'll be able to call Spawn from Update. I'm doing some timer management in my project and it works like a champ. Hope that helps! Here's a little code to illustrate:
public float spawnTimerMax;
public float spawnTimer;
void Start()
{
spawnTimerMax = 10f;
spawnTimer = spawnTimerMax;
}
void Update()
{
spawnTimer -= Time.deltaTime;
if(score > 100 && spawnTimerMax > 7f)
{ spawnTimerMax = 7f; }
//other score checking here
//Check timer and spawn
if(spawnTimer <= 0f)
{
Spawn();
spawnTimer = spawnTimerMax;
}
}