/
ObjectPoolerScript.cs
79 lines (60 loc) · 1.61 KB
/
ObjectPoolerScript.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
71
72
73
74
75
76
77
78
79
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach this script to a ObjectPooler gameobject.
public class ObjectPoolerScript : MonoBehaviour
{
public static ObjectPoolerScript currentObjectPoolerScript;
public GameObject pooledObject;
public int pooledAmount = 20;
//if I call for an object that isnt available, will I create a new object and add to pool,will my pool grow/expand ?
public bool willGrow = true;
List<GameObject> pooledObjects;
private void Awake()
{
currentObjectPoolerScript = this;
}
void Start()
{
pooledObjects = new List<GameObject>();
for(int i = 0; i < pooledAmount; i++)
{
GameObject obj = (GameObject) Instantiate(pooledObject);
obj.SetActive(false);
pooledObjects.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < pooledObjects.Count; i++)
{
if (!pooledObjects[i].activeInHierarchy)
{
return pooledObjects[i];
}
}
if (willGrow)
{
GameObject obj = (GameObject) Instantiate(pooledObject);
pooledObjects.Add(obj);
return obj;
}
return null;
}
//in BulletFireScript attached to gun/warship etc. it ffires bullets repeatedly from the gun.
//void Start()
//{
// InvokeRepeating("Fire", fireTime, fireTime);
//}
//void Fire()
//{
// GameObject obj = ObjectPoolerScript.currentObjectPoolerScript.GetPooledObject();
// if(obj == null)
// {
// return;
// }
// obj.transform.position = transform.position;
// obj.transform.rotation = transform.rotation;
// obj.SetActive(true);
//}
}