My goal was to create a big invisible cube and inside that spawn small random cubes.
These small cubes would have:
- A random position within the big cube.
- A random colour.
- A random size.
- A random lifetime.
- A higher chance to spawn with offset of 0 on y-axis than any other
offset. - Ability to rotate in sync with the big cube.
- Ability to fade away as it ages.
- To be replaced with new random cubes as they expire.
To achieve this, here is the code I wrote:
SpawnCube.cs
public GameObject smallCubePrefab;
public float rateOfSpawn = 1;
private float nextSpawn = 0;
// Update is called once per frame
void Update()
{
// Spawn new cubes at specified spawn rate
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + rateOfSpawn;
StartCoroutine(FadeOutCube());
}
}
public List<GameObject> SpawnSmallCubes()
{
// Create an empty list of cubes
List<GameObject> 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 FadeOutCube()
{
// Give random lifetime
float fadeSpeed = Random.Range(0.01f, 0.05f);
List<GameObject> smallCubes = SpawnSmallCubes();
foreach (GameObject cube in smallCubes.ToArray())
{
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;
}
if(cube.GetComponent<Renderer>().material.color.a <= 0)
{
Destroy(cube);
smallCubes.Remove(cube);
}
}
}
Rotate.cs
public Vector3 rotationSpeed;
// Update is called once per frame
void Update()
{
transform.Rotate(rotationSpeed * Time.deltaTime);
}
Any suggestions for improvement or changes to make it better in any way?
Thanks