If you aren't sure if a pool exists there are two ways you can handle it, depending on what you want to do with the results of the test. For the following examples, assume there is a variable 'poolName' which holds the name of the pool we want to test for. E.g. string poolName = "Enemies"; Example 1 // ContainsKey() returns true or false. See documentation for ContainsKey()
// Using the 'bang' or 'is-not'-exclamation-point inverts the result, so // true is false and false is true if (!PoolManager.Pools.ContainsKey(poolName))
{ Debug.Log("PoolManager does not contain a pool named " + poolName);
return; }
// Now we know the pool exists, we can use it. PoolManager.Pools[poolName].Spawn(myPrefab); Example 2 The following is the fastest way to test if a pool exists AND get a reference to the pool to use it. If you don't need the out-value reference, just use Contains (for example, if you just want to quit rather than work with the pool) // Create a variable which will be set in TryGetValue() below SpawnPool pool; // TryGetValue() returns the same as Containts() but also offers and out value // see documentation for TryGetValue() if (!PoolManager.Pools.TryGetValue(poolName, out pool))
{ Debug.Log("PoolManager does not contain a pool named " + poolName);
return; }
// Not only do we know the pool exists, but we also have a reference to it // so we can use it immediately pool.Spawn(myPrefab); |
Example Patterns >