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
71
72
| const { ccclass, property } = cc._decorator
@ccclass
export class ccPool extends cc.Component {
private poolNode: Map<string, cc.Node[]> = new Map()
public clear(key: any) {
if (this.poolNode.has(key)) {
this.poolNode.get(key).forEach((item) => {
item.active = false
item.destroy()
})
this.poolNode.delete(key)
}
}
public clearAll() {
this.poolNode.forEach((item, key) => {
item.forEach((item2) => {
item2.active = false
item2.destroy()
})
this.poolNode.delete(key)
})
}
public recycle(node: cc.Node) {
node.active = false
}
public recycleKey(key: string) {
if (this.poolNode.has(key)) {
this.poolNode.get(key).forEach((item) => {
item.active = false
})
}
}
public create(_key: any, _prefab: cc.Node, _position: cc.Vec3): cc.Node {
let _node = this.findUsabale(_key)
if (_node != null) {
// 如果有可用的对象
_node.position = _position
_node.active = true
} else {
// 如果没有可用的对象
_node = cc.instantiate(_prefab)
_node.position = _position
_node.active = true
_node.parent = this.node
this.addObject(_key, _node)
}
return _node
}
private findUsabale(key: string): cc.Node | null {
if (!this.poolNode.has(key)) return null
const _node = this.poolNode.get(key).find((item) => !item.active)
return _node
}
/**
* 添加到 poolnode
* @param key
* @param node
*/
private addObject(key: string, node: cc.Node) {
if (!this.poolNode.has(key)) this.poolNode.set(key, [])
this.poolNode.get(key).push(node)
}
}
|
使用说明
cocos creator 挂载节点上 所有的对象会添加到子节点当中
复用仅仅是更改对象节点的 active
尽可能的复用节点
1
2
3
4
| //创建
cc.Pool.create(key, prefab, position);
// 回收
ccPool.recycle(node);
|