Elin Decompiled Documentation EA 23.102 Nightly
Loading...
Searching...
No Matches
ObjectPool.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using UnityEngine;
4
5public class ObjectPool : MonoBehaviour
6{
7 public interface IItem
8 {
9 void Update();
10 }
11
12 public class Item<T> : IItem where T : new()
13 {
14 public Stack<T> pools;
15
16 public int max;
17
18 public int addsPerUpdate;
19
20 public Action<T> onCreate;
21
22 public Component mold;
23
24 public void Create(int _max, int _addsPerUpdate = 10)
25 {
26 max = _max;
27 addsPerUpdate = _addsPerUpdate;
28 pools = new Stack<T>(_max);
29 }
30
31 public T Get(Component parent)
32 {
33 T obj = ((pools.Count > 0) ? pools.Pop() : Create());
34 Component obj2 = obj as Component;
35 obj2.transform.SetParent(parent.transform, worldPositionStays: false);
36 obj2.SetActive(enable: true);
37 return obj;
38 }
39
40 public T Get()
41 {
42 if ((bool)mold)
43 {
44 Debug.LogError("tried to Get component");
45 }
46 if (pools.Count > 0)
47 {
48 return pools.Pop();
49 }
50 return Create();
51 }
52
53 public void Update()
54 {
55 for (int i = 0; i < addsPerUpdate; i++)
56 {
57 if (pools.Count >= max)
58 {
59 break;
60 }
61 pools.Push(Create());
62 }
63 }
64
65 public T Create()
66 {
67 T val;
68 if ((bool)mold)
69 {
70 val = Util.Instantiate(mold, Instance).GetComponent<T>();
71 (val as Component).SetActive(enable: false);
72 }
73 else
74 {
75 val = new T();
76 }
77 if (onCreate != null)
78 {
79 onCreate(val);
80 }
81 return val;
82 }
83
84 public Item<T> SetMold(Component _mold)
85 {
86 mold = _mold;
87 return this;
88 }
89
90 public override string ToString()
91 {
92 return typeof(T).Name + ":" + pools.Count;
93 }
94 }
95
96 public static ObjectPool Instance;
97
98 public List<IItem> items = new List<IItem>();
99
100 private void Awake()
101 {
102 Instance = this;
103 }
104
105 private void Update()
106 {
107 foreach (IItem item in items)
108 {
109 item.Update();
110 }
111 }
112
113 public static Item<T> Create<T>(int max = 100, int addsPerUpdate = 10, Action<T> _onCreate = null) where T : new()
114 {
115 Item<T> item = new Item<T>();
116 item.Create(max, addsPerUpdate);
117 item.onCreate = _onCreate;
118 Instance.items.Add(item);
119 return item;
120 }
121}
void Create(int _max, int _addsPerUpdate=10)
Definition: ObjectPool.cs:24
Item< T > SetMold(Component _mold)
Definition: ObjectPool.cs:84
override string ToString()
Definition: ObjectPool.cs:90
Component mold
Definition: ObjectPool.cs:22
Action< T > onCreate
Definition: ObjectPool.cs:20
Stack< T > pools
Definition: ObjectPool.cs:14
T Get(Component parent)
Definition: ObjectPool.cs:31
void Awake()
Definition: ObjectPool.cs:100
static Item< T > Create< T >(int max=100, int addsPerUpdate=10, Action< T > _onCreate=null)
Definition: ObjectPool.cs:113
void Update()
Definition: ObjectPool.cs:105
static ObjectPool Instance
Definition: ObjectPool.cs:96
List< IItem > items
Definition: ObjectPool.cs:98