首先我们要明白为什么要建立内存池?
它的作用在于优化性能,因为在射击类的游戏中不断的创建与销毁游戏对象相当消耗性能,所以我们可以通过把暂时不用的游戏资源设置为未激活状态,待需要使用时将该游戏资源设置成激活状态,这样避免了一味的新创建与销毁
using UnityEngine;
using System.Collections;using System.Collections.Generic;
using System;
public class PoolManager
{
//内存池集合
private static List<GameObject> pools = new List<GameObject>();
//提供给用户:创建游戏对象
public static GameObject CreatObj(string name)
{
GameObject go = null;
foreach (GameObject item in pools)//遍历列表
{
if (item.name.Contains(name) && item.activeSelf == false)//创建对象存在于列表中且未被激活
{
go = item;
item.SetActive(true);
return go;//激活该对象并返回
}
}
if (go == null)//1.列表中没有我们要找的对象 2.有我们要找的对象但是都在使用中
{ //在Resources文件夹下,复制该对象
GameObject temp = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>(name));
if (temp == null)
{
throw new Exception("没有该预设");
}
go = temp;
pools.Add(go);//添加列表并返回
}
return go;
}
//删除游戏对象
public static void Destory(GameObject go)
{
go.SetActive(false);//将对象设置成未激活状态
}
}