| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | namespace DCL.ECS7.ComponentWrapper.Generic |
| | 6 | | { |
| | 7 | | public record WrappedComponentPool<T> where T: class, IWrappedComponent |
| | 8 | | { |
| | 9 | | private readonly Func<T> objectFactory; |
| | 10 | | private readonly List<T> list; |
| | 11 | |
|
| 85 | 12 | | public WrappedComponentPool(int capacity, Func<T> objectFactory) |
| | 13 | | { |
| 85 | 14 | | list = new List<T>(capacity); |
| 85 | 15 | | this.objectFactory = objectFactory; |
| 85 | 16 | | } |
| | 17 | |
|
| | 18 | | public PooledWrappedComponent<T> Get() |
| | 19 | | { |
| 96 | 20 | | if (list.Count == 0) |
| | 21 | | { |
| 93 | 22 | | return new PooledWrappedComponent<T>(objectFactory(), this); |
| | 23 | | } |
| | 24 | |
|
| 3 | 25 | | int index = list.Count - 1; |
| 3 | 26 | | T wrappedComponent = list[index]; |
| 3 | 27 | | wrappedComponent.ClearFields(); |
| 3 | 28 | | PooledWrappedComponent<T> result = new PooledWrappedComponent<T>(wrappedComponent, this); |
| 3 | 29 | | list.RemoveAt(index); |
| 3 | 30 | | return result; |
| | 31 | | } |
| | 32 | |
|
| | 33 | | public void Release(PooledWrappedComponent<T> element) |
| | 34 | | { |
| 20 | 35 | | for (int i = 0; i < list.Count; i++) |
| | 36 | | { |
| 0 | 37 | | if (list[i] == element.WrappedComponent) |
| | 38 | | { |
| | 39 | | #if UNITY_EDITOR |
| 0 | 40 | | Debug.LogError($"element {typeof(T)} already released to the pool"); |
| | 41 | | #endif |
| 0 | 42 | | return; |
| | 43 | | } |
| | 44 | | } |
| | 45 | |
|
| 10 | 46 | | list.Add(element.WrappedComponent); |
| 10 | 47 | | } |
| | 48 | | } |
| | 49 | | } |