forked from UnityCommunity/UnityLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPool.cs
84 lines (71 loc) · 2.55 KB
/
Pool.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
80
81
82
83
84
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace UnityHelper.Pooling
{
[Serializable]
public class Pool
{
/// <summary>
/// The objects that you want to add to the pool
/// </summary>
public List<PoolObject> objects_to_pool = new List<PoolObject>();
/// <summary>
/// All the objects that were added to the pool
/// </summary>
private List<GameObject> pool_objects = new List<GameObject>();
/// <summary>
/// Initializes the pool in your scene
/// </summary>
public void Start_Pool()
{
var pool = new GameObject("Pool");
foreach (var item in objects_to_pool)
{
var sub_parent = new GameObject(item.obj_to_pool.name);
for (int i = 0; i < item.amount_to_pool; i++)
{
var _obj = UnityEngine.Object.Instantiate(item.obj_to_pool);
_obj.transform.SetParent(sub_parent.transform, false);
_obj.SetActive(false);
pool_objects.Add(_obj);
}
sub_parent.transform.SetParent(pool.transform, false);
}
}
/// <summary>
/// Gets the item from the pool and spawns it at the required position
/// </summary>
/// <param name="type">The type of script in the pool that you need to spawn</param>
/// <param name="position">The position where you want the item to spawn</param>
/// <returns>A component of the needed type</returns>
public Component Spawn_Item(Type type, Vector3 position, Quaternion direction)
{
foreach (GameObject item in pool_objects)
{
Component comp = null;
item.TryGetComponent(type, out comp);
if (comp == null)
continue;
if (item.activeSelf)
continue;
item.transform.position = position;
item.transform.rotation = direction;
item.SetActive(true);
return comp;
}
return null;
}
/// <summary>
/// Brings the item back to the pool
/// </summary>
/// <param name="item">The item to bring back to the pool</param>
public void Return_Item(GameObject item)
{
item.SetActive(false);
item.transform.position = Vector3.zero;
}
}
}