Random GameObject Spawn over time?

Hey guys,

I’m trying to get a certain gameobject to spawn at specific spawn points (which I’ve allocated with empty gameobjects) which is all working dandy but now I want the object to spawn at random times which then spawn faster over time (increases in amount spawned every minute or so). They do not need to move or anything, just spawn in the one location.

I’m pretty new to coding and I’ve attached what I’ve got so far. Any help would be greatly appreciated!

  • using System.Collections;
    • public class Spawn : MonoBehaviour {
  • public Transform spawnPoint;
  • public Transform spawnObject;
  • public int spawnTotal;
  • public float timeBetweenSpawns;
    • // Use this for initialization
  • void Start () {
  • StartCoroutine (SpawnGameObject ());
  • }
    • // Update is called once per frame
  • void Update () {
    • }
  • IEnumerator SpawnGameObject(){
  • for ( var x = 0 ; x < spawnTotal; x++) {
  • Instantiate (spawnObject, spawnPoint.position, spawnPoint.rotation);
  • yield return new WaitForSeconds (timeBetweenSpawns);
    • }
      • }
  • }

Hey. I’d be inclined to move the coroutine and move your spawning logic in to the Update method. If you add a float variable to your class definition (the same place you declare your public variables) you can set that to the time you next want to spawn an object. (You’d also need to remove your for loop.) Something like:

private float _nextSpawnTime;
private int _currentSpawnCount;

void Update()
{
    // if we need to spawn more and the time says we can spawn another one
    if (_currentSpawnCount < spawnTotal && Time.time <= _nextSpawnTime)
    {
        // Do the spawn logic here (Instantiate())
      
        // change you time between spawns
        timeBetweenSpawns -= 0.1;

        // set up variables for next Update call
        _nextSpawnTime = Time.time + timeBetweenSpawns;
        _currentSpawnCount++;
    }
}

Though this method does mean you need to decrease _currentSpawnCount whenever you remove one of the objects.