Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.1K
Vistas
¿Cómo generar un número determinado de cubos aleatorios juntos y después de que estos cubos desaparezcan, generar otro conjunto de cubos en Unity?

Actualmente, mi escena genera un cubo a la vez a una tasa de generación específica. Entonces, después de cada 5 segundos, aparece un nuevo cubo y se desvanece lentamente y desaparece después de un corto tiempo.

Sin embargo, ahora quiero hacer que, por ejemplo, aparezcan 5 cubos juntos y, una vez que desaparezcan, quiero que aparezcan 5 cubos nuevos.

Probablemente solo sea un cambio simple que debo hacer para esto, pero realmente no puedo resolverlo.

Aquí está mi código hasta ahora, pero no estoy seguro de por dónde seguir de aquí en adelante:

 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); } }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Actualmente, genera solo un cubo y lo agrega a una nueva lista. Más tarde, desvanece todos los cubos (actualmente solo uno) a la vez con la misma duración de desvanecimiento.

Para mí, parece que preferirías diferentes duraciones de desvanecimiento para cada cubo.

Preferiría dividirlo y tener una rutina para cada cubo individual.

Además, no hay necesidad de crear una nueva lista cada vez. Por el contrario, mantenga la lista existente y solo agregue y elimine elementos. De esta manera, también puede usar directamente la lista y verificar si el cubo que está eliminando es el último y, en ese caso, iniciar una nueva generación de grupos.

algo como esto

 // Use the correct type for the prefab so you don't need GetComponent at all public Renderer smallCubePrefab; // How many cubes shall be spawned min/max randomly? public int minCubes = 1; public int maxCubes = 10; // Create this list only ONCE // Later simply add spawned cubes and remove the destroyed ones // => Trigger a new group spawn if the list is empty private readonly List<Renderer> cubesList = new List<Renderer>(); private void Start() { // Trigger initial group spawn SpawnCubes(); } private void SpawnCubes() { // Pick random amoun // +1 since upper parameter is exclusive for int var amount = Random.Range(minCubes, maxCubes + 1); // Start individual Coroutine for each cube for(var i = 0; i < amount; i++) { StartCoroutine (SpawnAnsFadeoutCube()); } } // This spawns 1 single cube and adds it to the existing list private Renderer GenerateCube() { // Spawn cube at random position within the big cube's transform position var randPosition = new Vector3(Random.Range(-0.5f, 0.5f), 0, Random.Range(-0.5f, 0.5f)); // Generate higher chance (2 chances in 3) of spawning small cubes with offset = 0 on Y-axis var randomY = new List<float>() {0, 0, Random.Range(-0.5f, 0.5f)}; randPosition.y = randomY[Random.Range(0, 3)]; randPosition = transform.TransformPoint(randPosition); // Spawn small cube // Will return Renderer since the prefab is now of type Renderer var smallCube = Instantiate(smallCubePrefab, randPosition, transform.rotation); // Give random color smallCube.material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); // Give random size var randSize = Random.Range(1, 10); smallCube.transform.localScale = Vector3.one * randSize; // Add spawned cube to the list of cubes cubesList.Add(smallCube); return smallCube; } private IEnumerator SpawnAndFadeOutCube() { // Give random lifetime var fadeSpeed = Random.Range(0.01f, 0.05f); var cube = GenerateCube(); var material = cube.material; // This routine is only responsible for this single cube! while (material.color.a > 0) { var cubeColor = material.color; var fadeAmount = cubeColor.a - (fadeSpeed * Time.deltaTime); cubeColor.a = fadeAmount); material.color = cubeColor; yield return null; } cubesList.Remove(cube); Destroy(cube.gameObject); // Was this the last cube? if(cubeList.Count == 0) { // Trigger next group spawn SpawnCubes(); } }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda