Question by
maszto · Aug 28, 2021 at 10:01 AM ·
object pool
Object Pooler problem with deactivating objects
Hi guys, I'm working with object pooling for the first time. I want to use it for spawning random enemies in loop. Works fine but when I kill the enemy he disappear but didn't deactivet ( not returning to the pool). I 've been looking for some solutions but nothing works. Of course gameObject.SetActive(false); also didn't work. Any ideas ?
There is my pooler script:
public class EnemiesPooler : MonoBehaviour
{
public static EnemiesPooler current;
public GameObject[] enemyPrefabs;
[SerializeField] private int enemiesPooledAmount;
[SerializeField] private bool willGrow;
private List<GameObject> pooledEnemies;
private void Awake()
{
current = this;
}
// Start is called before the first frame update
void Start()
{
pooledEnemies = new List<GameObject>();
GameObject enemy;
for (int i = 0; i<enemiesPooledAmount; i++)
{
int randEnemy = Random.Range(0, enemyPrefabs.Length);
enemy = Instantiate(enemyPrefabs[randEnemy]);
enemy.SetActive(false);
pooledEnemies.Add(enemy);
}
}
public GameObject GetPooledEnemy()
{
for (int i = 0; i < enemiesPooledAmount; i++)
{
if (!pooledEnemies[i].activeInHierarchy)
{
return pooledEnemies[i];
}
}
if (willGrow)
{
int randEnemy = Random.Range(0, enemyPrefabs.Length);
GameObject enemy = Instantiate(enemyPrefabs[randEnemy]);
pooledEnemies.Add(enemy);
return enemy;
}
return null;
}
}
Comment