private PoolObjectComponent ReturnToPool(PoolObjectComponent component) { var next = firstAvailable; firstAvailable = component; return(next); }
public static PoolObjectComponent AddComponentTo(GameObject target, PoolObjectComponent next, Func <PoolObjectComponent, PoolObjectComponent> returnCallback) { var component = target.AddComponent <PoolObjectComponent>(); component.next = next; component.returnToPool = returnCallback; return(component); }
public void Clear() { firstAvailable = null; foreach (var poolObject in objects) { UnityEngine.Object.Destroy(poolObject.gameObject); } objects.Clear(); }
private void OnDisable() { // when object become a not active in hierarchy // make it free for use in the pool if (returnToPool == null) { return; } next = returnToPool(this); }
private GameObject InstantiateAndAddToPool() { var go = UnityEngine.Object.Instantiate(prefab); if (container != null) { go.transform.SetParent(container); } var poolObject = PoolObjectComponent.AddComponentTo(go, firstAvailable, ReturnToPool); go.SetActive(false); objects.Add(poolObject); return(go); }
/// <summary> /// Get first available or create new object /// </summary> /// <returns>GameObject instance</returns> public GameObject Create() { // if no one object in the PoolObjectComponent linked list or reach the end of the list // instantiate and add that new instance to linked list if (firstAvailable.next == null) { InstantiateAndAddToPool(); } // return current first available object from list // and set next object as first available var obj = firstAvailable; firstAvailable = obj.next; return(obj.gameObject); }