position and object pool


In my game after a certain amount of Y distance has been traveled. I instantiate an obstacle prefab that holds some random variables.
This works fine as it is right now.
However after a while it get’s laggy because the “older” objects aren’t removed.
I looked into object pools but I can’t seem to get this one to work.

So in short, I am looking for a way to position a clone of the original gameobject to the scene. And when the index is 3 delete them all except for the last added one, and the one before that. So I always have enough “obstactles” in my scene.

I thought it would be somewhat simple. But maybe i can’t see it anymore… Kind of stuck here.
Any help is welcome!

    void Update () {
    		//if player player somes 6 units distance from its last distance ,then we will create new bar group
    		if( playerTransform != null && playerTransform.position.y - lastPlayerPosition > travelUnitsForDistance)
    			lastPlayerPosition = playerTransform.transform.position.y; // to store the present ball position y .

   void createNewGroup()
		barGroupNewInstance = GameObject.Instantiate(barGroup) as GameObject;
		barGroupNewInstance.transform.position = new Vector3(-3,distanceBetweenBarGroups*groupIndex,0 );


Could one help out?
Many thanks


By working with queues (as opposed to stacks), you’re working on a first-in, first-out basis. You add to the queue, then if the queue is too large, remove the first object from it. In your case, you would destroy the first GameObject in the queue, then remove it from the queue when you add a new GameObject to the end of the queue.