I want the: Spawn(_wave.hostage) to happen randomly once while the enemys of the wave spawn. currently the hostage only spawns at the end.
any ideat what i need to change?
thanks in advance
IEnumerator SpawnWave (Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.Spawning;
//Spawn
for(int i = 0; i < _wave.count; i++)
{
Spawn(_wave.enemy);
yield return new WaitForSeconds(1f/_wave.rate); //wait for x seconds
}
for(int i = 0; i < _wave.hostageCount; i++)
{
Spawn(_wave.hostage);
}
state = SpawnState.Waiting;
Debug.Log("Waiting");
yield break;
}
void Spawn(Transform _enemy)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
for (int i = 0; i < maxTries; i++)
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
if (oldSpawnPoint != spawnPoints[spawnPointIndex])
{
Transform _sp = spawnPoints[spawnPointIndex];
oldSpawnPoint = _sp;
Instantiate(_enemy, _sp.position, _sp.rotation);
break;
}
else
{
Debug.Log("Spawning Position Already Used");
}
}
}
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.Spawning;
StartCoroutine(SpawnHostages(_wave));
for(int i = 0; i < _wave.count; i++)
{
Spawn(_wave.enemy);
yield return new WaitForSeconds(1f/_wave.rate);
}
state = SpawnState.Waiting;
Debug.Log("Waiting");
yield break;
}
IEnumerator SpawnHostages(Wave _wave)
{
// Calculating how many enemies do we spawn and in how much time, so we know the time interval in which we can spawn hostages
float totalSpawnInterval = _wave.count * (1f/_wave.rate);
// We have to spawn X hostages (_wave.hostageCount). So we need an array in which we generate some random time intervals. We will use those intervals to pause the coroutine.
List<float> spawnIntervals = new List<float>();
for(int i = 0; i < _wave.hostageCount; i++) spawnIntervals.Add(Random.Range(0, totalSpawnInterval));
// We sort these values and convert them into intervals rather than points in time.
spawnIntervals.Sort();
for (int i = spawnIntervals.Count - 1; i > 0; i--) spawnIntervals *-= spawnIntervals[i - 1];*
// We start spawning
for(int i = 0; i < _wave.hostageCount; i++)
{
yield return new WaitForSeconds(spawnIntervals*);*
Spawn(_wave.hostage);
}
}
This function will try to spawn hostages in the time interval in which enemies spawn, but using WaitForSeconds too many times in a short time interval can make it take longer. The solution could be:
- Not relying on WaitForSeconds for precise time calculations
- Using WaitForSeconds and each time it spawns an enemy, subtract the extra time it took to spawn from the interval list
- Not using the total spawn interval, but only 80-90% of it (totalSpawnInterval * 0.8)
It all depends on how accurate you need to be with the two coroutines.