I am a novice in unity.
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
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);
}
}