/// <summary>This allows you to despawn a clone via GameObject, with optional delay.</summary> public static void Despawn(GameObject clone, float delay = 0.0f) { if (clone != null) { var pool = default(SlothPool); // Try and find the pool associated with this clone if (Links.TryGetValue(clone, out pool) == true) { // Remove the association Links.Remove(clone); pool.Despawn(clone, delay); } else { if (SlothPool.TryFindPoolByClone(clone, ref pool) == true) { pool.Despawn(clone, delay); } else { Debug.LogWarning("You're attempting to despawn a gameObject that wasn't spawned from this pool", clone); // Fall back to normal destroying Object.Destroy(clone); } } } else { Debug.LogWarning("You're attempting to despawn a null gameObject", clone); } }
/// <summary>Find the pool responsible for handling the specified prefab.</summary> public static bool TryFindPoolByPrefab(GameObject prefab, ref SlothPool foundPool) { for (var i = Instances.Count - 1; i >= 0; i--) { var pool = Instances[i]; if (pool.Prefab == prefab) { foundPool = pool; return(true); } } return(false); }
/// <summary>This allows you to spawn a prefab via GameObject.</summary> public static GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent) { if (prefab != null) { // Find the pool that handles this prefab var pool = default(SlothPool); // Create a new pool for this prefab? if (SlothPool.TryFindPoolByPrefab(prefab, ref pool) == false) { pool = new GameObject("LeanPool (" + prefab.name + ")").AddComponent <SlothPool>(); pool.Prefab = prefab; } // Try and spawn a clone from this pool var clone = default(GameObject); if (pool.TrySpawn(position, rotation, parent, ref clone) == true) { // Clone already registered? if (Links.Remove(clone) == true) { // If this pool recycles clones, then this can be expected if (pool.Recycle == true) { } // This shouldn't happen else { Debug.LogWarning("You're attempting to spawn a clone that hasn't been despawned. Make sure all your Spawn and Despawn calls match, you shouldn't be manually destroying them!", clone); } } // Associate this clone with this pool Links.Add(clone, pool); return(clone); } } else { Debug.LogError("Attempting to spawn a null prefab"); } return(null); }
/// <summary>Find the pool responsible for handling the specified prefab clone. /// NOTE: This can be an expensive operation if you have many large pools.</summary> public static bool TryFindPoolByClone(GameObject clone, ref SlothPool pool) { for (var i = Instances.Count - 1; i >= 0; i--) { pool = Instances[i]; // Search hash set if (pool.spawnedClonesHashSet.Contains(clone) == true) { return(true); } // Search list for (var j = pool.spawnedClonesList.Count - 1; j >= 0; j--) { if (pool.spawnedClonesList[j] == clone) { return(true); } } } return(false); }