-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectPool.cs
More file actions
42 lines (36 loc) · 881 Bytes
/
ObjectPool.cs
File metadata and controls
42 lines (36 loc) · 881 Bytes
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
using UnityEngine;
using System.Collections.Generic;
public class ObjectPool<T> : MonoBehaviour where T : Component
{
public T prefab;
private Queue<T> pool = new Queue<T>();
public void Initialize(T prefab, int initialCount)
{
this.prefab = prefab;
for (int i = 0; i < initialCount; i++)
{
AddObjectToPool();
}
}
public T GetObject()
{
if (pool.Count == 0)
{
AddObjectToPool();
}
T obj = pool.Dequeue();
obj.gameObject.SetActive(true);
return obj;
}
public void ReturnObject(T obj)
{
obj.gameObject.SetActive(false);
pool.Enqueue(obj);
}
private void AddObjectToPool()
{
T newObject = Instantiate(prefab);
newObject.gameObject.SetActive(false);
pool.Enqueue(newObject);
}
}