- Home /
Spawning a set amount of game objects that replaces the objects as they're destroyed
I'm attempting to have 25 objects spawn that fall to the bottom from the top. I'm also trying to have it to where once an object is hit, another spawns at the top to take it's place. the problem I'm having with this is that the coroutine spawns as many as it pleases and floods the screen. I figure it's because the yield keeps the thing from running until two seconds have passed. is there any way that I can salvage this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Drop_Cube : MonoBehaviour
{
public GameObject largeChunk;
public Rigidbody2D largeChunkRB;
public int maxCubes;
public static float globalMaxCubes;
public int cubeSpawnRate;
// Start is called before the first frame update
void Start()
{
globalMaxCubes = 0;
largeChunkRB.AddForce(-Vector2.up, ForceMode2D.Impulse);
}
// Update is called once per frame
void Update()
{
if (globalMaxCubes <= maxCubes)
{
globalMaxCubes += Time.deltaTime * cubeSpawnRate;
StartCoroutine(droppingCubes());
}
}
IEnumerator droppingCubes()
{
Vector3 cubeDispersion = new Vector3(Random.Range(-7f, 7f), Random.Range(-4f, 4f), Random.Range(0f, 0f));
yield return new WaitForSeconds(1f);
Instantiate(largeChunk, transform.position + cubeDispersion, (transform.rotation));
Debug.Log(globalMaxCubes);
}
}
Answer by jkpenner · Apr 21, 2020 at 02:10 AM
Check to make sure that cubeSpawnRate is not set to zero in the inspector. If it is set to zero the globalMaxCubes variable will never increase and will always be below maxCubes.
The logic in your update function needs to be changed. Right know if you increase your cubeSpawnRate it could increase the globalMaxCubes count by 2 or more and only spawn one cube. This could lead to it thinking your at the max cubes, when only a few cubes are spawned.
To fix these issues I'd recommend changing your update method by using a variable for the amount of cubes spawned and another for a counter to determine when to spawn the cubes. Something similar to this:
// Decrease a counter by the delta time.
spawnCounter -= Time.deltaTime;
// Only spawn cubes when the counter is at 0 and when
// we are below the max allowed cube count.
if (spawnCounter <= 0f && curSpawned < maxSpawned) {
// Reset the spawn counter
spawnCounter = this.spawnDelay;
// Increase the current number of spawned cubes
curSpawned++;
// Handle spawning the new cube
StartCoroutine(droppingCubes());
}
thank you for the assistance, this saved me several hours of going further in the wrong direction