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!
Answer by LuckierBread · Jul 16, 2016 at 05:55 AM
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. $$anonymous$$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.
You would propably just have to throw a Random.Range(x,y) in there. You can use it to let the bot spawn in a random location (int recommended, because it gives more variation. Float could be to close together). For the spawn time I would just have the decreasing spawn time + a Random.Range(2,4). The spawn time will decrease while they will still spawn randomly.
Hope this helps!
@LuckierBread How would I add the lines of code in the script to what @Donkey$$anonymous$$alonkey 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