forked from Unity-Technologies/FPSSample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkObjectPool.cs
More file actions
54 lines (45 loc) · 1.27 KB
/
NetworkObjectPool.cs
File metadata and controls
54 lines (45 loc) · 1.27 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
using System;
using System.Collections.Generic;
using UnityEngine;
// TODO : Optimize internal data structures
public class NetworkObjectPool<T> where T : class, new()
{
public int allocated { get { return m_Allocated.Count; } }
public int capacity { get { return m_Allocated.Capacity; } }
public NetworkObjectPool(int initialSize, Func<T> factory = null)
{
Grow(initialSize);
m_Factory = factory;
}
public T Allocate()
{
if (m_Free.Count == 0)
Grow(m_Free.Capacity * 2);
var element = m_Free[m_Free.Count - 1];
m_Free.RemoveAt(m_Free.Count - 1);
m_Allocated.Add(element);
return element;
}
public void Release(T t)
{
bool result = m_Allocated.Remove(t);
GameDebug.Assert(result);
m_Free.Add(t);
}
public void Reset()
{
foreach (var item in m_Allocated)
m_Free.Add(item);
m_Allocated.Clear();
}
void Grow(int count)
{
m_Free.Capacity += count;
m_Allocated.Capacity += count;
for (int i = 0; i < count; ++i)
m_Free.Add(m_Factory != null ? m_Factory() : new T());
}
Func<T> m_Factory;
List<T> m_Free = new List<T>();
List<T> m_Allocated = new List<T>();
}