Reputation: 156
I have created a script for generating enemies at the scene. It is a wave based enemy generator, a group of enemies get generated then it waits until all of them are dead and then goes to the next round. Here is the code:
while (GameObject.FindGameObjectWithTag("Player") != null)
{
Spawner();
if (waveCount == 1)
{
sound.clip = startRoundAlert;
sound.Play();
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
waveCount++;
}
else if (waveCount == 2)
{
if(GameObject.FindGameObjectsWithTag("Enemy").Length == 0)
{
sound.clip = endRoundAlert;
sound.Play();
roundText.text = "Get ready for round" + waveCount;
yield return new WaitForSeconds(waveWait);
roundText.text = "";
sound.clip = startRoundAlert;
sound.Play();
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
yield return new WaitForSeconds(4);
Spawner();
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
waveCount++;
}
}
else if (waveCount == 3)
{
if (GameObject.FindGameObjectsWithTag("Enemy").Length == 0)
{
sound.clip = endRoundAlert;
sound.Play();
roundText.text = "Get ready for round" + waveCount;
yield return new WaitForSeconds(waveWait);
roundText.text = "";
sound.clip = startRoundAlert;
sound.Play();
Instantiate(enemyz[1], SpawnPoint, Quaternion.identity);
waveCount++;
}
}
This script works correctly but after checking with unity profiler I think it is not optimized enough. If anyone has a suggestion for making it better I would be really happy to hear it.
Upvotes: 0
Views: 73
Reputation: 7412
Alright, I tried to clean up your game loop a bit - but really your code would cut out early anyway because you have the Enemy check before doing any work - so I think this is really more just a cleaning up of the code.
I think to really help you with performance, we'd need to see some of the other methods - and it would be great if you could say why you think it's not optimized
while(GameObject.FindGameObjectWithTag("Player") != null)
{
Spawner(); //What does this do?
if(GameObject.FindGameObjectsWithTag("Enemy").Length == 0)
{
StartNextRound();
waveCount++;
}
}
private void StartNextRound()
{
switch(waveCount)
{
case 1:
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
break;
case 2:
NewRoundSetup()
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
yield return new WaitForSeconds(4);
Spawner();
Instantiate(enemyz[0], SpawnPoint, Quaternion.identity);
break;
case 3:
NewRoundSetup()
Instantiate(enemyz[1], SpawnPoint, Quaternion.identity);
break;
}
}
private void NewRoundSetup()
{
sound.clip = endRoundAlert;
sound.Play();
roundText.text = "Get ready for round" + waveCount;
yield return new WaitForSeconds(waveWait);
roundText.text = "";
sound.clip = startRoundAlert;
sound.Play();
}
Upvotes: 1