- Home /
The Object you want to instantiate is null when using pool system
Hello, I created a pool system for bullets. When I try to instantiate a bullet it tells me "The Object you want to instantiate is null"
Here is the script for the pool system
public class BulletPool : MonoBehaviour
{
public static BulletPool instance;
[SerializeField] GameObject bulletPrefab;
Queue<GameObject> bullets;
void Start()
{
if (bulletPrefab == null)
{
Debug.Log("error null");
}
if (instance == null)
{
instance = new BulletPool();
instance.bullets = new Queue<GameObject>();
}
}
public void AddToQueue(GameObject bullet)
{
bullet.SetActive(false);
instance.bullets.Enqueue(bullet);
}
public GameObject GetBullet()
{
GameObject bullet;
if (instance.bullets.Count > 0)
bullet = instance.bullets.Dequeue();
else
bullet = Instantiate(bulletPrefab); // that's where the error is
return bullet;
}
}
I added the prefab bullet to the script.
Anybody see what is wrong? Thank you for your help!
Answer by unity_ek98vnTRplGj8Q · Jan 06, 2021 at 10:47 PM
You actually have two instances of BulletPool. The first instance is the one that is attached to your game object. You make a second instance which you have called "instance", and this is the one that is throwing the error because it does not have the reference to the bullet prefab, while your first one does. To fix it, just change
if (instance == null)
{
instance = new BulletPool();
instance.bullets = new Queue<GameObject>();
}
to
if (instance == null)
{
instance = this;
instance.bullets = new Queue<GameObject>();
}
or something along those lines, whatever you want to to make sure that you only have the 1 instance of bullet pool.