-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameObjectPool.cs
More file actions
96 lines (78 loc) · 3.13 KB
/
GameObjectPool.cs
File metadata and controls
96 lines (78 loc) · 3.13 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace X
{
public class GameObjectPool
{
class ObjectPoolItem
{
// public DateTime LastInstantiateTime;
public Stack<GameObject> GameObjects = new Stack<GameObject>();
}
class ObjectPoolParameter : MonoBehaviour
{
public int InstanceID;
}
Transform RecycleBin;
Dictionary<int?, ObjectPoolItem> ObjectPoolItems = new Dictionary<int?, ObjectPoolItem>();
public GameObjectPool(Transform recycleBin)
{
RecycleBin = recycleBin;
}
bool CreateObjectPoolItem(GameObject go, out int instanceID, out ObjectPoolItem item)
{
instanceID = 0;
item = null;
var parameter = go.GetComponent<ObjectPoolParameter>();
if (parameter == null)
return false;
instanceID = parameter.InstanceID;
if (ObjectPoolItems.TryGetValue(instanceID, out item))
return true;
item = new ObjectPoolItem();
ObjectPoolItems[instanceID] = item;
return true;
}
public GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation)
{
int instanceID = original.GetInstanceID(); // 缓存池创建时不检查GUID参数,因为外部可能进行改变
ObjectPoolItem item;
if (!ObjectPoolItems.TryGetValue(instanceID, out item))
{
var newObj = GameObject.Instantiate(original, position, rotation) as GameObject;
var parameter = newObj.AddMissingComponent<ObjectPoolParameter>();
parameter.InstanceID = instanceID;
newObj.BroadcastMessage("OnSpawned", SendMessageOptions.DontRequireReceiver);
return newObj;
}
var obj = item.GameObjects.Pop();
if (item.GameObjects.Count == 0)
ObjectPoolItems.Remove(instanceID);
obj.transform.SetParent(null, false);
obj.transform.position = position;
obj.transform.rotation = rotation;
obj.BroadcastMessage("OnSpawned", SendMessageOptions.DontRequireReceiver);
return obj;
}
public GameObject Instantiate(GameObject original)
{
return Instantiate(original, original.transform.position, original.transform.rotation);
}
public void Destroy(GameObject go)
{
int instanceID;
ObjectPoolItem item;
if (!CreateObjectPoolItem(go, out instanceID, out item))
{
go.transform.SetParent(RecycleBin, false);
GameObject.Destroy(go);
return;
}
go.BroadcastMessage("OnDespawned", SendMessageOptions.DontRequireReceiver);
go.transform.SetParent(RecycleBin, false);
item.GameObjects.Push(go);
}
}
}