GameObject and C# Stacks

I’m currently creating an object pool to reuse objects from in Unity. In the main game manager, I define the stack.

public static Stack baseMissileBulletStack = new Stack();

I then initialize the projectiles:

GameObject newBullet = (GameObject)Instantiate((GameObject) mainGameManager.weapBulletPrefabs.baseMissileBullet, Vector3.zero, 
				Quaternion.identity);

To remove an object from the stack, I use:

GameObject newProjectile = (GameObject) PlayerBulletPool.baseMissileBulletStack.Pop() 

And this is where the error kicks in during run-time:

InvalidCastException: Cannot cast from source type to destination type.

Remove the (GameObject) case and you get this compile error:

 Cannot implicitly convert type `object' to `UnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?)

So basically, I cannot remove an object from the stack without casting it, and Unity doesn’t acknowledge it at run time anyway. Even if I made newProjectile an Object type, there’s no way to convert it into a GameObject. How do I make this work?

I managed to solve this problem on my own. I changed the definition of the stack to:

public static Stack<GameObject> baseMissileBulletStack = new Stack<GameObject>();

This allowed me to make a specific type of stack and thus everything ended up working.

Note that more often, what you want is a QUEUE, not a Stack.

A queue is first in first out (FIFO).

FIFO is a more common need in games.

For example, a script which follows another transform - but with a delay of some frames. (So, something like snake-parts following each other.)

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

public class DelayFollow : MonoBehaviour {

	[Header("The object 'ahead' of you in the snake...")]
	public Transform leadingMe;
	private int gapInFrames = 15;
	
	private Queue<Vector3> q = new Queue<Vector3>();
	
	void Update () {
		
		q.Enqueue(leadingMe.localEulerAngles);
		if (q.Count < gapInFrames) { return; }
		transform.localEulerAngles = q.Dequeue();
	}
}