[Solved] How to put a limit on the spawn rate?

using UnityEngine;
using System.Collections;
   
public class SpawnOverTime : MonoBehaviour
{

        public GameObject[] testObject;
        public float xRange = 1.0f;
        public float yRange = 1.0f;
        public float minSpawnTime = 0.6f;
        public float maxSpawnTime = 0.6f;
        private float lastIncreased;
        private float timeDelay = 1;
   
        // Use this for initialization
        void Start ()
        {

                Invoke ("SpawnItem", Random.Range (minSpawnTime, maxSpawnTime));

        }

        void Update ()
        {

                if (Time.time > timeDelay + lastIncreased) {
                        lastIncreased = Time.time;
                        minSpawnTime -= 0.05f;
                        maxSpawnTime -= 0.05f;

                }

        }
   
        // Update is called once per frame
        void SpawnItem ()
        {

                float xOffset = Random.Range (-xRange, xRange);
                float yOffset = Random.Range (-yRange, yRange);
                int spawnObjectIndex = Random.Range (0, testObject.Length);
                GameObject goInst = (GameObject)Instantiate (testObject [spawnObjectIndex], transform.position + new Vector3 (xOffset, yOffset, 0.0f), testObject [spawnObjectIndex].transform.rotation);
                goInst.transform.parent = transform;
                Invoke ("SpawnItem", Random.Range (minSpawnTime, maxSpawnTime));
        }
}

Hi this is my code for spawning it decreases the timer over time but eventually it goes into negatives! Can someone tell me how to put a limit on the spawn? Like it should end at 0.15f and stay there. Thank you.

Just curious, but your minspawn and maxspawn are the exact same number. Why are you using random.range?

Otherwise, if you plan to do a reduction like you’re doing. Just check if your spawnTime is >.15f, if it is, reduce it, if not, then don’t touch the value.

Hi thanks yes they are the same I left it so if wanted to do a random spawn can just use it later. But for now don’t need random spawn range. I am not really good at code but do I do something like this?

     if ((maxSpawnTime) < 1) {
       maxSpawnTime = 1f;

Since in update, you have this

if (Time.time > timeDelay + lastIncreased) {
                        lastIncreased = Time.time;
                        minSpawnTime -= 0.05f;
                        maxSpawnTime -= 0.05f;
                }

But you could have this

if (Time.time > timeDelay + lastIncreased && maxSpawnTime > .15f) {
                        lastIncreased = Time.time;
                        maxSpawnTime -= 0.05f;
                }

This way once maxspawntime is == .15f, it will no longer reduce.

1 Like

Thank you kind person.