0%

对象池参考模板

代码如下:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Poolspace
{
public abstract class PoolBase<T> : IEnumerable<T>
{
public List<T> inactiveObjectsPool { get; protected set; }
public List<T> activeObjectsPool { get; protected set; }
public Transform rootObject { get; protected set; }
public T baseObject { get; protected set; }
public int startSize { get; protected set; }

protected PoolBase(string _PoolName,T baseObject, int startSize = 32,Transform Path=null)
{
this.baseObject = baseObject;
this.startSize = startSize;
this.activeObjectsPool = new List<T>(startSize);
inactiveObjectsPool = new List<T>(startSize);


rootObject = Path ? Path : new GameObject(_PoolName).transform;
Init();
}

private void Init()
{
for (int i = 0; i < startSize; i++)
{
Instantiate();
}
}

public abstract T Instantiate();

public abstract T Get(bool createWhenNoneLeft = true);

public abstract void Destroy(T item);

public void DestroyAll()
{
int num = 0;
while (activeObjectsPool.Count > 0 && num++ < startSize)
Destroy(activeObjectsPool[0]);
}

public IEnumerator<T> GetEnumerator()
{
return activeObjectsPool.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}


}

}