Currently my scene spawns one cube at a time at a specific spawn rate. So after every 5 seconds, a new cube spawns and it slowly fades away and disappears after a short time.
However, I now want to make it so that for example 5 cubes spawn together and once they all disappear, I want new 5 cubes to spawn.
Probably just a simple change I need to do for this but I really can't figure it out.
Here is my code so far but not sure where to go about from here on:
public GameObject smallCubePrefab;
public float rateOfSpawn = 1;
private float nextSpawn = 0;
List<GameObject> cubesList;
// Update is called once per frame
void Update()
{
// Spawn new cubes at specified spawn rate
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + rateOfSpawn;
StartCoroutine(SpawnAndFadeOutCube());
}
}
public List<GameObject> GenerateCubes()
{
// Create an empty list of cubes
cubesList = new List<GameObject>();
// Spawn cube at random position within the big cube's transform position
Vector3 randPosition = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));
// Generate higher chance (2 chances in 3) of spawning small cubes with offset = 0 on Y-axis
List<float> randomY = new List<float>() {0, 0, Random.Range(-1f, 1f)};
randPosition.y = randomY[Random.Range(0, 3)];
randPosition = transform.TransformPoint(randPosition * .5f);
// Spawn small cube
GameObject smallCube = Instantiate(smallCubePrefab, randPosition, transform.rotation);
// Give random color
smallCube.GetComponent<Renderer>().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
// Give random size
int randSize = Random.Range(1, 10);
smallCube.transform.localScale = new Vector3(randSize, randSize, randSize);
// Add spawned cube to the list of cubes
cubesList.Add(smallCube);
return cubesList;
}
public IEnumerator SpawnAndFadeOutCube()
{
// Give random lifetime
float fadeSpeed = Random.Range(0.01f, 0.05f);
List<GameObject> smallCubes = GenerateCubes();
foreach (GameObject cube in smallCubes)
{
while (cube.GetComponent<Renderer>().material.color.a > 0)
{
Color cubeColor = cube.GetComponent<Renderer>().material.color;
float fadeAmount = cubeColor.a - (fadeSpeed * Time.deltaTime);
cubeColor = new Color(cubeColor.r, cubeColor.g, cubeColor.b, fadeAmount);
cube.GetComponent<Renderer>().material.color = cubeColor;
yield return null;
}
Destroy(cube);
}
}