How would I create a script that spawns objects more frequently as time goes on, then stops after a certain point/amount of time?

For my game, I have an enemy that works perfectly. Now how would I make a mode, in which the enemy spawns more frequently as time goes on, then the spawn rate just stays the same the whole time. The reason I am asking this is because I have a script for my camera to where it gets faster and faster than stays at the same speed for the rest of the game. I have no idea where to start with a script like this, so any help would be appreciated.
Here is the spawn enemy script.

using UnityEngine;
using System.Collections;

public class SpawnEnemy : MonoBehaviour {

	public GameObject[] obj;
	public float spawnMin = 1f;
	public float spawnMax = 2f;

	// Use this for initialization
	void Start () {
		Spawn ();
	
	}
	
	// Update is called once per frame
	void Spawn () {
		Instantiate (obj [Random.Range (0, obj.GetLength (0))], transform.position, Quaternion.identity);
		Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
	
	}
}

Thanks for helping!

1 Answer

1

I’m no pro,
But I would use a coroutine a for loop and a while loop.
I wrote some code below go ahead and see if it satisfies your needs just remember that the spots I left for you to fill in are floats.

Also make sure you select this answer if it helped.

void Start()
{
    StartCoroutine(SpawnSpeed());
}

IEnumerator SpawnSpeed()
{
    for (float Time = ("Time between first and second spawn");
         Time > ("min time between spawns"); 
         Time -= ("how much time you want to cut between spawns") )
    {
        Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
        yield return new WaitForSeconds (Time);
    }
    while(true)
    {
        Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
        yield return new WaitForSeconds("min time between spawns");
    }
}

@LuckierBread Thank you so much! However, I need the objects to spawn randomly within a specific timeframe, except not spawning too close to each other at the same time. E.g., the objects spawn between 2 and 4 seconds without getting too close to each other. Also, I want the player to either have to jump over one object at a time or two objects if the objects are close together.

@LuckierBread How would I add the lines of code in the script to what @DonkeyMalonkey said?

@LuckierBread Thank you so much! But i'm just not sure where to put the line of code. Could you show where to put it?

I didn't mean position. I meant spawning like something between 2 and 4 seconds. @LuckierBread