Delete the oldest gameobject

I have a land gameobject that will spawn upon collision with one of its kind. I also want to remove the first one if there are 3 or more in the game already. I’m able to spawn the game object fine, I’m stuck in how to detect if there are three game object in game already. I tried using a list but it will always be 1 because the script fire on the new gameobject. The script is attached to the ground object.

Here is my script for creating

        public class platform : MonoBehaviour {
            public GameObject groundprefab;
            private bool generated;
            int removecounter = 3;

            // Use this for initialization
            void Start () {
                generated = false;      
            }

            private void OnCollisionEnter(Collision other)
            {
                if (other.gameObject.tag=="player")
                {
                    GameObject groundinstance;
                    if (generated == false)
                    {
                        switch (Random.Range(1, 3))
                        {
                            case 1:
                                groundinstance = Instantiate(groundprefab, new Vector3(groundprefab.transform.position.x + 0, groundprefab.transform.position.y + 0, groundprefab.transform.position.z + 10), new Quaternion(0, 0, 0, 0)) as GameObject;
                                generated = true;
                                break;
                            case 2:
                                groundinstance = Instantiate(groundprefab, new Vector3(groundprefab.transform.position.x + -10, groundprefab.transform.position.y + 0, groundprefab.transform.position.z + 0), new Quaternion(0, groundprefab.transform.eulerAngles.y + -90, 0, 0)) as GameObject;
                                generated = true;
                                break;
                            case 3:
                                groundinstance = Instantiate(groundprefab, new Vector3(groundprefab.transform.position.x + 10, groundprefab.transform.position.y + 0, groundprefab.transform.position.z + 0), new Quaternion(0, groundprefab.transform.eulerAngles.y + 90, 0, 0)) as GameObject;
                                generated = true;
                                break;
                        }
                    }
                }
            }

        }

Many thanks.

Good day.

I dont exactly understand what you want, but if is what i think…

You can use Tags for each type of object.
When you use GameObject.FindObjectsWithTag(“Tag”) you get an array with all elements in the scene at that time with the mentioned tag.

so, If this array.length >= 3 means you can destroy one of the objects.

How to recognise the oldestone?

You should have a “master script” that will assign numbers to each object, to know ther order they was spawned, so you can always know which is the oldest.

Bye!