-4

I am making a objectpoolingManager which is supposed to put bullets under an empty object called objectpoolingManager and in my code i wrote that it must enable the bullet when i click the mouse button then after 2 second it will diables the bullet now my problem is that it is always disabled.

public GameObject bulletPrefab;
public int bulletAmount = 20;

private List<GameObject> bullets;

// Start is called before the first frame update
void Awake()
{
    instance = this;
    bullets = new List<GameObject>(bulletAmount);

    for (int i = 0; i < bulletAmount;i++)
    {
        GameObject prefabInstance = Instantiate (bulletPrefab);
        prefabInstance.transform.SetParent (transform);
        prefabInstance.SetActive(false);
    }

    bullets.Add(bulletPrefab);
}

public GameObject GetBullet ()
{
    foreach (GameObject bullet in bullets)
    {
        if(!bullet.activeInHierarchy)
        {
            bullet.SetActive (true);
            return bullet;
        }
    }
    GameObject prefabInstance = Instantiate (bulletPrefab);
    prefabInstance.transform.SetParent (transform);
    bullets.Add(bulletPrefab);

    return prefabInstance;
}
}
jps
  • 20,041
  • 15
  • 75
  • 79
abdallah
  • 9
  • 1
  • your get method does not make much sense, you reinstantiate the bullet prefab and set it as parent of the gameobject of the shown script gameobject, which is supposed to be the bullet manager... – rustyBucketBay Mar 27 '21 at 13:20

1 Answers1

1

Your getter/setter of objects in your pool manager should not instantiate or destroy gamobjects, but enable and disable them. That is the purpose of pooling. It makes more sense to EnQueue/deQueue them and activate/deactivate like this.

private Queue<GameObject> objPool;
private Queue<GameObject> activeObj;
//get from pool
public GameObject GetObjFromPool(Vector3 newPosition, Quaternion newRotation)
{
    GameObject newObject = objPool.Dequeue();
    newObject.SetActive(true);
    newObject.transform.SetPositionAndRotation(newPosition, newRotation);

    //keep actives to be retrieved
    activeObj.Enqueue(newObject);
    return newObject;
}

//return to pool
public void ReturnObjToPool(GameObject go)
{
    go.SetActive(false);
    objPool.Enqueue(go);
}

Find this question in case its helpfull.

You can find plenty of pooling examples if you goolgle that up. Here is one.

rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47