Unity场景中经常需要动态生成一些预制体物体,记录分享方便快捷的对象池使用方式。
public GameObject prefab;
public GameObject pool;// 对象池游戏物体
private Dictionary<string, Queue<GameObject>> objectPool = new Dictionary<string, Queue<GameObject>>();// 对象池字典,(string对象名字,对象队列)
///
<summary>
/// 从对象池中获取预制体生成的对象
/// </summary>
/// <param name="tprefab"></param>
/// <returns></returns>
public GameObject GetObject(GameObject tprefab)
{
GameObject _object;
Debug.Log(tprefab.name);
//如果对应池子里没有该可用对象
if (!objectPool.ContainsKey(tprefab.name) || objectPool[tprefab.name].Count == 0)
{
_object = GameObject.Instantiate(tprefab);//实例化对象,加入队列
PushObject(_object);//存储对象到对应池子,并设置为隐藏
_object.transform.SetParent(pool.transform);//存放到对应池子物体位置下
}
_object = objectPool[tprefab.name].Dequeue();//对应池子中的对象出列。
_object.SetActive(true);
return _object;
}
/// <summary>
/// 过期的物体加入对象池存储起来
/// </summary>
/// <param name="prefab"></param>
public void PushObject(GameObject prefab)
{
//string _name = prefab.name.Replace("(Clone)", string.Empty);
//如果字典中没有对应的key值,则新建一条数据
if (!objectPool.ContainsKey("MarkerPoint"))
objectPool.Add("MarkerPoint", new Queue<GameObject>());
//对象入列
objectPool["MarkerPoint"].Enqueue(prefab);
prefab.SetActive(false);
}
/// <summary>
/// 字符串转Vector3
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public Vector3 S2VParse(string str)
{
str = str.Replace("(", " ").Replace(")", " ");
string[] s = str.Split(',');
return new Vector3(float.Parse(s[0]), float.Parse(s[1]), float.Parse(s[2]));
}