About Enqueue NullReferenceException problem

I am a novice in unity. :rofl:

I encounter a problem about the use of Queue.
After generating and creating the queue, I can only take out the object. When I try to use Enqueue(), a NullReferenceException error will appear(Called in other scripts). Below is my code. hope to get help :rofl:

public Queue<GameObject> enemyPool;
public static EnemyPoolM instance;
public int poolNum = 5;
private void Awake()
{
    instance = this;
}
void Start()
{
    enemyPool = new Queue<GameObject>();
    GameObject enemy = null;
    for (int i = 0; i < poolNum; i++)
    {
        enemy = Instantiate(enemy1_prefab);
        enemy.SetActive(false);
        enemyPool.Enqueue(enemy);
    }
}
public GameObject GetEnemy()
{
    if (enemyPool.Count>0)
    {
        GameObject enemy = enemyPool.Dequeue();
        enemy.SetActive(true);
        return enemy;
    }
    else
    {
        return Instantiate(enemy1_prefab);
    }
}
public void RecoverEnemy(GameObject obj)
{
    obj.SetActive(false);
    **enemyPool.Enqueue(obj);**       //Here is the problematic code 
}

Below is my code for calling this method in other scripts.

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        enemy = this.gameObject;
        EnemyPoolM.instance.RecoverEnemy(enemy);
    }
}

Hi @biaodianduan,

This is a difficult problem to diagnose from the forefront.

Have you tried to debug your code? With debugging you will be able to see what GameObject is coming into RecoverEnemy.

The definition of the exception is:
A NullReferenceException happens when you try to access a reference variable that isn’t referencing any object.

So if we go off of that, the GameObject obj of **enemyPool.Enqueue(obj);** is null OR your queue itself is null, though its most probably the former.

As a simple check you could do this:

public void RecoverEnemy(GameObject obj)
{
    if(obj == null){
        Debug.Log("Object Null");
    }

    if (enemyPool == null)
    {
        Debug.Log("Queue is null");
    }
    
    obj.SetActive(false);
    **enemyPool.Enqueue(obj);**       //Here is the problematic code 
}

TL;DR :smiley:

In this instance your queue is null - This is due to using a singleton pattern for your object.

One way to resolve is to remove the queue initialisation from the start function and make it static. private static Queue<GameObject> enemyPool = new Queue<GameObject>();

Hope that helps!

hi @RussianBsack
Thank you for your reply!! :laughing:
I followed your way to debug, and the result surprised me.
Duge.Lod shows: Queue is null !!
This confuses me a bit. I have already generated how the queue will become null. :rofl: