wangguan
2020-12-23 1e192494412a34d17548834a6aff639202cdfdda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections.Generic;
using UnityEngine;
 
namespace Core.Utilities
{
    /// <summary>
    /// Managers a dictionary of pools, getting and returning 
    /// </summary>
    public class PoolManager : Singleton<PoolManager>
    {
        /// <summary>
        /// List of poolables that will be used to initialize corresponding pools
        /// </summary>
        public List<Poolable> poolables;
 
        /// <summary>
        /// Dictionary of pools, key is the prefab
        /// </summary>
        protected Dictionary<Poolable, AutoComponentPrefabPool<Poolable>> m_Pools;
 
        /// <summary>
        /// Gets a poolable component from the corresponding pool
        /// </summary>
        /// <param name="poolablePrefab"></param>
        /// <returns></returns>
        public Poolable GetPoolable(Poolable poolablePrefab)
        {
            if (!m_Pools.ContainsKey(poolablePrefab))
            {
                m_Pools.Add(poolablePrefab, new AutoComponentPrefabPool<Poolable>(poolablePrefab, Initialize, null,
                                                                                  poolablePrefab.initialPoolCapacity));
            }
 
            AutoComponentPrefabPool<Poolable> pool = m_Pools[poolablePrefab];
            Poolable spawnedInstance = pool.Get();
 
            spawnedInstance.pool = pool;
            return spawnedInstance;
        }
 
        /// <summary>
        /// Returns the poolable component to its component pool
        /// </summary>
        /// <param name="poolable"></param>
        public void ReturnPoolable(Poolable poolable)
        {
            poolable.pool.Return(poolable);
        }
 
        /// <summary>
        /// Initializes the dicionary of pools
        /// </summary>
        protected void Start()
        {
            m_Pools = new Dictionary<Poolable, AutoComponentPrefabPool<Poolable>>();
 
            foreach (var poolable in poolables)
            {
                if (poolable == null)
                {
                    continue;
                }
                m_Pools.Add(poolable, new AutoComponentPrefabPool<Poolable>(poolable, Initialize, null,
                                                                            poolable.initialPoolCapacity));
            }
        }
 
        void Initialize(Component poolable)
        {
            poolable.transform.SetParent(transform, false);
        }
    }
}