Copy elements from one list to another list
Hello,
I'm making a 2D space shooter game and I'm making some waves of enemies. I have these waves saved in a List called
waveConfigs
I'm making the game to spawn waves in random order and loop that, but I only want the waves used once per loop. so for example there are 4 waves and the game starts with wave 2, then that wave can't be used until the next loop. For that part I made 2 other lists called
availableWaves and usedWaves
availableWaves contains all the waves and usedWaves is empty, once the game start and a wave is spawned. that wave is removed from the availableWaves and added to usedWaves, once all waves are used and the loop starts I want to clear usedWaves list to make it empty again. I want to copy the elements from waveConfigs back to availableWaves. Ofcourse when I write the code: ''availableWaves = waveConfigs'' then the result isn't right as after the second loop the elements from waveConfigs are also removed as shown in the link https://youtu.be/3LxEJpzAOug.
Also after the second loop no more enemies are spawning because of that.
My question is how to copy the elements from waveConfigs to availableWaves without waveConfigs being modified.
Here's the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemySpawner : MonoBehaviour {
[SerializeField] int startingWave = 0;
[SerializeField] bool looping = false;
[SerializeField] List<WaveConfig> waveConfigs;
[SerializeField] List<WaveConfig> availableWaves;
[SerializeField] List<WaveConfig> usedWaves;
// Start is called before the first frame update
IEnumerator Start()
{
// once all waves have spawned, it goes to "while". in while it will loop back to the coroutine
do
{
yield return StartCoroutine(SpawnAllWaves());
}
while (looping);
}
// Update is called once per frame
void Update()
{
}
private IEnumerator SpawnAllWaves()
{
for (int waveIndex = startingWave; waveIndex < availableWaves.Count; waveIndex++)
{
var currentWave = availableWaves[Random.Range(waveIndex, availableWaves.Count)];
yield return StartCoroutine(SpawnAllEnemiesInWave(currentWave));
availableWaves.Remove(currentWave);
usedWaves.Add(currentWave);
Debug.Log(currentWave);
if (availableWaves.Count <= 0)
{
usedWaves.Clear();
}
}
}
private IEnumerator SpawnAllEnemiesInWave(WaveConfig waveConfig)
{
for(int enemyCount = 0; enemyCount < waveConfig.GetNumberOfEnemies(); enemyCount++)
{
var newEnemy = Instantiate
(waveConfig.GetEmemyPrefab(),
waveConfig.GetWaypoints()[0].transform.position,
Quaternion.identity);
newEnemy.GetComponent<EnemyPathing>().SetWaveConfig(waveConfig);
yield return new WaitForSeconds(waveConfig.GetTimeBetweenSpawns());
}
}
In the method SpawnAllWaves is where the elements are being added/removed