-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameObjectPooler.cs
More file actions
87 lines (74 loc) · 2.5 KB
/
GameObjectPooler.cs
File metadata and controls
87 lines (74 loc) · 2.5 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using UnityEngine;
using System.Collections.Generic;
public class GameObjectPooler : MonoBehaviour {
public static GameObjectPooler Instance;
private Dictionary<string, List<GameObject>> ObjectPool;
void Awake() {
Instance = this;
this.ObjectPool = new Dictionary<string, List<GameObject>>();
}
public void PreloadGameObject(GameObject prefab) {
var nameOfPrefab = this.GetPrefabName(prefab);
var gameObject = this.InstatiateNewGameObject(prefab);
this.AddToObjectPool(gameObject, nameOfPrefab);
}
public GameObject GetObject(GameObject prefab) {
var nameOfPrefab = this.GetPrefabName(prefab);
GameObject gameObject;
if(this.ObjectPool.ContainsKey(nameOfPrefab) && this.HasInactiveGameObject(nameOfPrefab)) {
gameObject = this.GetInactiveGameObject(nameOfPrefab);
}
else {
gameObject = this.InstatiateNewGameObject(prefab);
this.AddToObjectPool(gameObject, nameOfPrefab);
}
return gameObject;
}
private string GetPrefabName(GameObject prefab) {
var nameOfPrefab = prefab.name.Replace("(Clone)", "");
return nameOfPrefab;
}
private bool HasInactiveGameObject(string nameOfPrefab) {
var hasInactiveGameObject = false;
foreach(GameObject gameObject in this.ObjectPool[nameOfPrefab]) {
if(!gameObject.activeInHierarchy) {
hasInactiveGameObject = true;
}
}
return hasInactiveGameObject;
}
private GameObject GetInactiveGameObject(string nameOfPrefab) {
GameObject gameObject = null;
foreach(GameObject pooledGameObject in this.ObjectPool[nameOfPrefab]) {
if(!pooledGameObject.activeInHierarchy) {
gameObject = pooledGameObject;
}
}
return gameObject;
}
private void AddToObjectPool(GameObject gameObject, string nameOfPrefab) {
if(this.ObjectPool.ContainsKey(nameOfPrefab)) {
this.AddObjectToExistingPool(gameObject, nameOfPrefab);
}
else {
this.AddToNewObjectPool(gameObject, nameOfPrefab);
}
}
private void AddToNewObjectPool(GameObject gameObject, string nameOfPrefab) {
var list = this.GetNewGameObjectList(gameObject);
this.ObjectPool.Add(nameOfPrefab, list);
}
private void AddObjectToExistingPool(GameObject gameObject, string nameOfPrefab) {
this.ObjectPool[nameOfPrefab].Add(gameObject);
}
private List<GameObject>GetNewGameObjectList(GameObject gameObject) {
var list = new List<GameObject>();
list.Add(gameObject);
return list;
}
private GameObject InstatiateNewGameObject(GameObject gameObject) {
gameObject = (GameObject)Instantiate(gameObject);
gameObject.SetActive(false);
return gameObject;
}
}