Unity チュートリアルのタワーディフェンステンプレートを触ってみる(49)

Unity チュートリアルのタワーディフェンステンプレートを触ってみる(48)では GameManager に合わせて追加した LevelManager の解説を行った。今回は Poolable ゲームオブジェクトの管理を行う PoolManager について解説を行っている。
1.タワーディフェンステンプレートのステージの設定編 – PoolManager.cs
PoolManager.cs について稚拙ながら解説
「PoolManager.cs」は「Assets/Scripts/Core/Utilities/PoolManager.cs」の指しておりスクリプトについては以下の通り。内容としては Poolable ゲームオブジェクトの管理を行っている。
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);
}
}
}
9行目 : 「public class PoolManager : Singleton<PoolManager>」はUnity チュートリアルのタワーディフェンステンプレートを触ってみる(46)で解説した Singleton を継承し、総称型として PoolManager を指定していることを指している。
26行目 : 「public Poolable GetPoolable(Poolable poolablePrefab)」はプールしているインスタンスの取得を行っている。内容としては m_Pools にゲームオブジェクトが登録されていなければ m_Pools を追加し、m_Pools からプールしているインスタンスを取得している。
45行目 : 「public void ReturnPoolable(Poolable poolable)」は pool の返却を行っている。
53行目 : 「protected void Start()」は Unity 固有の開始処理を行っている。内容としては登録している、poolables から m_Pools に追加している。
68行目 : 「void Initialize(Component poolable)」は poolable に対して PoolableManager を Parent として追加している