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
70 lines (60 loc) · 1.65 KB
/
Copy pathObjectPool.cs
File metadata and controls
70 lines (60 loc) · 1.65 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
// 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;
internal Func<T> CreateFunc;
public int maxSize
{
get { return m_MaxSize; }
set
{
m_MaxSize = Math.Max(0, value);
while (Size() > m_MaxSize)
{
Get();
}
}
}
public ObjectPool(Func<T> CreateFunc, int maxSize = 100)
{
this.maxSize = maxSize;
if (CreateFunc == null)
{
this.CreateFunc = () => new T();
}
else
{
this.CreateFunc = CreateFunc;
}
}
public int Size()
{
return m_Stack.Count;
}
public void Clear()
{
m_Stack.Clear();
}
public T Get()
{
T evt = m_Stack.Count == 0 ? CreateFunc() : 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);
}
}
}
}