-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefabPool.cs
More file actions
78 lines (73 loc) · 1.92 KB
/
PrefabPool.cs
File metadata and controls
78 lines (73 loc) · 1.92 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Class to initialize prefab instances of frequently used GameObjects
* take them back, and assign them again when needed.
*/
public class PrefabPool : MonoBehaviour {
[SerializeField]
GameObject prefab;
List<GameObject> _activeObjects;
//Objects in play
List<GameObject> ActiveObjects
{
get
{
if(_activeObjects == null)
{
_activeObjects = new List<GameObject>();
}
return _activeObjects;
}
}
List<GameObject> _availableObjects;
//inactive objects that can be issued
List<GameObject> AvailableObjects
{
get
{
if(_availableObjects == null)
{
_availableObjects = new List<GameObject>();
}
return _availableObjects;
}
}
public GameObject GetObject()
{
GameObject obj;
if (AvailableObjects.Count > 0)
{
obj = AvailableObjects[0];
AvailableObjects.RemoveAt(0);
try
{
obj.SetActive(true);
}
catch (MissingReferenceException e)
{
Debug.LogError("MRE from " + gameObject.name);
throw e;
}
}
else
{
//None available, so create a new one
obj = Instantiate(prefab);
}
//Prep the object for the game world before returning
obj.transform.parent = null;
obj.transform.position = Vector3.zero;
obj.transform.rotation = Quaternion.identity;
obj.transform.localScale = Vector3.one;
ActiveObjects.Add(obj);
return obj;
}
public void ReturnObject(GameObject obj)
{
obj.SetActive(false);
ActiveObjects.Remove(obj);
AvailableObjects.Add(obj);
}
}