forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectPool.cs
More file actions
60 lines (51 loc) · 1.39 KB
/
ObjectPool.cs
File metadata and controls
60 lines (51 loc) · 1.39 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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEngine.UIElements
{
class ObjectPool<T> where T : new()
{
private readonly Stack<T> m_Stack = new Stack<T>();
private int m_MaxSize;
public int maxSize
{
get { return m_MaxSize; }
set
{
m_MaxSize = Math.Max(0, value);
while (Size() > m_MaxSize)
{
Get();
}
}
}
public ObjectPool(int maxSize = 100)
{
this.maxSize = maxSize;
}
public int Size()
{
return m_Stack.Count;
}
public void Clear()
{
m_Stack.Clear();
}
public T Get()
{
T evt = m_Stack.Count == 0 ? new T() : m_Stack.Pop();
return evt;
}
public void Release(T element)
{
if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element))
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
if (m_Stack.Count < maxSize)
{
m_Stack.Push(element);
}
}
}
}