Hello.
The classic space shooter. Initially, had player lasers being instantiated and destroyed. Saw pooling would make more sense.
However, once I pooled, the behavior of my lasers changed. The laser would randomly collide with the player ship. I have the collision matrix setup to the player ship and laser cannot collide. I’ve also tried ignoring the collision in the code as well.
Other strange behavior is when the player is moving, randomly lasers simply deactivate when traveling through space.
I did the classic pooling for space shooter type games in unity tutorials. It is just so odd code nor the collision matrix will not prevent the collision from happening.
First, I’m not using the built in pooling as my project was initiated with 2019.
I found this code online:
public class ObjectPool : MonoBehaviour
{
public static ObjectPool SharedInstance;
public Queue<GameObject> pooledObjects = new Queue<GameObject>();
[SerializeField] public GameObject objectToPool;
[SerializeField] int amountToPool = 50;
private void Awake()
{
SharedInstance = this;
SetupSingleton();
}
void Start()
{
GameObject tempGameObj;
for (int i = 0; i< amountToPool; i++)
{
tempGameObj = Instantiate(objectToPool);
tempGameObj.SetActive(false);
pooledObjects.Enqueue(tempGameObj);
}
}
public GameObject GetPooledObject()
{
if (pooledObjects.Count < 0)
{
GameObject laser = pooledObjects.Dequeue();
laser.SetActive(true);
FindObjectOfType<RedLaserBehavior>().PlayShootSound();
return laser;
}
else
{
GameObject laser = Instantiate(objectToPool);
FindObjectOfType<RedLaserBehavior>().PlayShootSound();
return laser;
}
}
public void ReturnLaserToPool(GameObject laser)
{
pooledObjects.Enqueue(laser);
laser.SetActive(false);
}
Then in my ship script:
{
laser = ObjectPool.SharedInstance.GetPooledObject();
if (laser != null)
{
laser.transform.position = gameObject.transform.position;
laser.transform.rotation = gameObject.transform.rotation;
}
}
yield return new WaitForSeconds(projectileFiringPeriod);
}
Returning laser to pool:
{
ObjectPool.SharedInstance.ReturnLaserToPool(gameObject);
Debug.Log(“Return small laser to pool”);
}
Now, I see another implementation in the unity tutorials I will try. The link is here: