Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Issue with Dictionary.containskey (Gameobject)

Discussion in 'Scripting' started by Erenquin, May 25, 2022.

  1. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Hello,
    I wanted to make a package out of my object pool handler implementation, while refactoring it a little in the process.
    It is working in a little game I did.

    My issue is when I try to "get" an object from the pool, the hash code is correct but still "containskey" return false.

    In Awake, containskey works as intended: if I want to create 2 pools with the same prefab it will prevent it.

    Thanks for the help :)

    Code (CSharp):
    1.         void Awake()
    2.         {
    3.  
    4.             foreach (var pool in pools)
    5.             {
    6.                 if (poolLookup.ContainsKey(pool.PrefabToPool))
    7.                 {
    8.                     Debug.LogError("Same object in multiple pools " + pool.PrefabToPool.name);
    9.                     continue;
    10.                 }
    11.  
    12.                 Debug.Log("Add : " + pool.PrefabToPool.name + " hash = " + pool.PrefabToPool.GetHashCode());
    13.                 poolLookup.Add(pool.PrefabToPool, pool);
    14.  
    15.                 GameObject parent = new GameObject("Pool: " + pool.PrefabToPool.name);
    16.                 parent.transform.parent = transform;
    17.                 pool.InitializePool(parent.transform);
    18.             }
    19.         }
    20.        
    21.         public GameObject Get(GameObject prefab)
    22.         {
    23.             if (poolLookup.ContainsKey(prefab))
    24.             {
    25.                 Debug.LogError(prefab.name + " not in pool : " + prefab.GetHashCode());
    26.                 return null;
    27.             }
    28.             return poolLookup[prefab].Get();
    29.         }
    upload_2022-5-25_18-43-7.png
     
  2. pixaware_pwedrowski

    pixaware_pwedrowski

    Joined:
    Oct 25, 2018
    Posts:
    116
    I think that your if statement is wrong, you probably want to check
    if (!poolLookup.ContainsKey(prefab))
    to return null instead
     
    Erenquin and Bunny83 like this.
  3. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Rofl, you must be correct.
    I did not realize that I removed the "!" at once.
    I can't test just right now but will very soon.

    Thanks a lot for the check.

    [Edit] No surprise that was the issue :rolleyes:
     
    Last edited: May 26, 2022