-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectPooler.cs
70 lines (56 loc) · 1.86 KB
/
ObjectPooler.cs
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
[System.Serializable]
public class Pool
{
public string tag;
public GameObject prefab;
public int size;
public List<Sprite> sprites;
}
public List<Pool> pools;
public Dictionary<string, List<Queue<GameObject>>> poolDict;
public static ObjectPooler Instance;
void Awake()
{
Instance = this;
poolDict = new Dictionary<string, List<Queue<GameObject>>>();
foreach (Pool pool in pools)
{
List<Queue<GameObject>> objPoolLst = new List<Queue<GameObject>>();
foreach (Sprite sprite in pool.sprites)
{
Queue<GameObject> objectPool = new Queue<GameObject>();
for (int i = 0; i < pool.size; i++)
{
GameObject obj = Instantiate(pool.prefab);
obj.GetComponent<SpriteRenderer>().sprite = sprite;
obj.SetActive(false);
objectPool.Enqueue(obj);
}
objPoolLst.Add(objectPool);
}
poolDict.Add(pool.tag, objPoolLst);
}
}
public GameObject spawnFromPool (float height, int colour)
{
string tag = getRandomDirection();
GameObject objToSpawn = poolDict[tag][colour].Dequeue();
objToSpawn.SetActive(true);
Vector3 pos = objToSpawn.transform.position;
pos.y = height;
objToSpawn.transform.position = pos;
poolDict[tag][colour].Enqueue(objToSpawn);
return objToSpawn;
}
private string getRandomDirection()
{
int random = Random.Range(0, 100);
if (random < 50) { return "left"; }
return "right";
}
}