- Home /
How do I use a Toggle to activate and deactivate scripts?
In my game I would like to be able to use 3 toggle buttons to toggle between 3 enemy difficulties. Difficulty is basically the amount of enemies spawned per second.
Easy = 1
Normal = 2
Hard = 3
The issue I am having is I can get it to activate and deactivate, but when I activate it again it basically stored all the enemies it has been spawning and releases them all at once.
To put it another way, if easy is selected 1 enemy should be spawned per second if Normal is selected Easy should be disabled and 2 troops should spawn per second. If I switch back to easy it should go back to one per second, and it does, but it also releases a massive flood of enemies that it has apparently been instantiating in the background while it was disabled.
{
public GameObject troopPrefab;
public Transform spawnPoint;
public Toggle easyToggle;
float i;
private void Update()
{
if (easyToggle.GetComponent<Toggle>().isOn == true)
{
EasySpawn();
}
if (easyToggle.GetComponent<Toggle>().isOn == false)
{
return;
}
}
public void EasySpawn()
{
if(Time.time > i)
{
i += 1f;
Instantiate(troopPrefab, spawnPoint.position, spawnPoint.rotation);
}
}
}
Answer by Bajtix · Jun 16, 2020 at 08:04 PM
I did some adjustments to your code, this should hopefully work. I tested it and it worked just fine for me. I added some comments, especially near the if statement.
public GameObject troopPrefab;
public Transform spawnPoint;
public Toggle easyToggle;
private float spawnTimer = 0f;
private void Update()
{
if (easyToggle.isOn)
/* instead of two if statements, it is better to utilise if-else.
Also, there no need to check [bool] == true, you can just put [bool].
And if you use a Toggle, you don't have to call easyToggle.GetComponent<Toggle>(), as it just returns itself.
*/
SpawnEnemies(1);
else
SpawnEnemies(2);
}
private void SpawnEnemies(int amount)
{
Debug.Log($"Spawning {amount} enemies"); //printing how many enemies were spawned to the console.
if (Time.time < spawnTimer) return;
for (int i = 0; i < amount; i++)
{
Instantiate(troopPrefab, spawnPoint.position, spawnPoint.rotation);
}
spawnTimer += 1f;
}