/// <summary> /// Adds to pool. /// </summary> /// <returns><c>true</c>, if item was successfully created, <c>false</c> otherwise.</returns> /// <param name="prefab">The prefab to instantiate new items.</param> /// <param name="count">The amount of instances to be created.</param> /// <param name="parent">The Transform container to store the items. If null, items are placed as parent</param> public bool AddToPool(GameObject prefab, int count, Transform parent = null, UtilFuncs.GameObjectModifier modifier = null) { if (prefab == null || count <= 0) { return(false); } for (int i = 0; i < count; i++) { GameObject obj = PopFromPool(prefab, true, false, parent, modifier); PushToPool(ref obj, true, parent); } return(true); }
private GameObject CreateObject(GameObject prefab, Transform container, UtilFuncs.GameObjectModifier modifier = null) { IPoolObject poolObjectPrefab = prefab.GetComponent <IPoolObject>(); if (poolObjectPrefab == null) { Debug.Log("Wrong type of object"); return(null); } GameObject obj = (GameObject)Object.Instantiate(prefab); numObjectsInstantiated++; IPoolObject poolObject = obj.GetComponent <IPoolObject>(); obj.name = prefab.name; poolObject.Prefab = prefab; obj.transform.parent = container; if (modifier != null) { modifier(obj); } return(obj); }
/// <summary> /// Pops item from pool. /// </summary> /// <returns>The from pool.</returns> /// <param name="prefab">Prefab to be used. Matches the prefab used to create the instance</param> /// <param name="forceInstantiate">If set to <c>true</c> force instantiate regardless the pool already contains the same item.</param> /// <param name="instantiateIfNone">If set to <c>true</c> instantiate if no item is found in the pool.</param> /// <param name="container">The Transform container to store the popped item.</param> public GameObject PopFromPool(GameObject prefab, bool forceInstantiate = false, bool instantiateIfNone = false, Transform container = null, UtilFuncs.GameObjectModifier modifier = null) { GameObject obj = null; if (forceInstantiate == true) { obj = CreateObject(prefab, null, modifier); } else { Queue <GameObject> queue = FindInContainer(prefab); if (queue.Count > 0) { obj = queue.Dequeue(); obj.SetActive(true); obj.transform.parent = container; } } if (obj == null && instantiateIfNone == true) { obj = CreateObject(prefab, container, modifier); } obj.GetComponent <IPoolObject> ().Init(); return(obj); }