Random instantiate limit

I have my script working great, It will randomly spawn the objects every ten seconds. But what I’m trying to do is limit the spawn to, let’s say ten, but I don’t want it to stop spawning in different places. I just don’t want more than ten on screen at one time, so as the tenth is spawned in it will delete the first. I’ve had a look through some answers but haven’t been able to find what I’m looking for.

I assume I need a variable to place the limit in, but from there I’m lost.

Any help is appreciated and if this question has already been asked, I apologize and would love the link to it.

Thanks.

Here’s my script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnObject : MonoBehaviour {

	public GameObject CollectiblePrefab;

	public Vector3 center;
	public Vector3 size;

	// Use this for initialization
	void Start () {
		InvokeRepeating ("SpawnCollectible", 10, 10);
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	public void SpawnCollectible(){
		Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2), Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));
		Instantiate(CollectiblePrefab, pos, Quaternion.identity);
	}

	void OnDrawGizmosSelected() {
		Gizmos.color = new Color(1,0,0,0.5f);
		Gizmos.DrawCube (center, size);
	}
}

here is a quick workaround (note that this is not best practice but will work)

add some tag to your object, let’s say “SomeTag”

you can change your code like that.

public void SpawnCollectible(){
if(objCount <= 10) objCount++;  //objCount is an integer variable
else Destroy(GameObject.FindGameObjectWithTag("SomeTag")); // this will find first gameobject with tag (witch is first created most of times) and destroys it
         Vector3 pos = center + new Vector3 (Random.Range (-size.x / 2, size.x / 2), Random.Range (-size.y / 2, size.y / 2), Random.Range (-size.z / 2, size.z / 2));
         Instantiate(CollectiblePrefab, pos, Quaternion.identity);

     }