Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Deleting object pools then recreating

Discussion in 'Scripting' started by LordMatthew, Sep 23, 2023.

  1. LordMatthew

    LordMatthew

    Joined:
    May 6, 2023
    Posts:
    13
    I have our object pools that are destroyed here on death
    Code (CSharp):
    1.     public void ResetAllPools()
    2.     {
    3.         ResetPool(diffitems);
    4.         ResetPool(items);
    5.     }
    6. public void ResetPool(List<PoolItem> passedInList)
    7.     {
    8.         foreach (PoolItem item in passedInList)  // references the list of prefabs
    9.         {
    10.             foreach (GameObject obj in item.objects)
    11.             {
    12.                   Destroy(obj);
    13.                // obj.SetActive(false);
    14.             }
    15.  
    16.             item.objects.Clear();
    17.         }
    18.  
    19.  
    20.     }
    But then on respawn/replay I need to create them again?

    They disappear from hierarchy but stay in pooled items; so when I run this script i end up with 2 or 3x the number of items/prefabs


    Code (CSharp):
    1.     ReAddPools(items, pooledItems);
    2.         ReAddPools(diffitems, diffpooledItems);
    3.  
    4.     }
    5.     public void ReAddPools(List<PoolItem> passedInList, List<GameObject> passIn)
    6.     {
    7.         foreach (PoolItem item in passedInList)  // references the list of prefabs
    8.         {
    9.             for (int i = 0; i < item.amount; i++)
    10.             {
    11.                 GameObject obj = item.prefab; //creates each obj prefab
    12.                 item.objects.Add(obj); // ******HERE*******
    13.                 obj.SetActive(false); // sets inactive by default
    14.                 passIn.Add(obj);  // then adds them to the pool
    15.             }
    16.         }
    This is the part which ends up creating 3x the objects sometimes ie we end up with 12 instead of 4 in the diffitems pool

    I thought the obj clear was just clearing them from hierarchy, so then i just need to put them back in there no?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
    Yet another thing to worry about. Are you sure you want to use pools?

    Personally I won't touch them until I know they matter. I'd rather write games!

    The costs and issues associated with object pooling / pools:

    https://forum.unity.com/threads/object-pooling.1329729/#post-8405055

    https://forum.unity.com/threads/object-pooling-in-a-tower-defense-game.1076897/#post-6945089
     
    SisusCo likes this.