# 结构\ 场景\ -挂在脚本的物体\ -- goModelParent\ --ToxicBornPointParent\然后把脚本挂上去按下T运行脚本```public List
# 结构\ 场景\ -挂在脚本的物体\ -- goModelParent\ --ToxicBornPointParent\
然后把脚本挂上去按下T运行脚本
```
public List goModelList = new List();//模型列表 public List toxicBornTransformList = new List();//模型的生成点 private List gameObjectsPool = new List();//创建的模型的对象的池子 public Transform goModelParent;//模型的父物体 public Transform ToxicBornPointParent;//模型生成点的父物体
void Start()
{
toxicBornTransformList = ToxicBornPointParent.transform.GetComponentsInChildren<Transform>().ToList();
}
void Update()
{
if (Input.GetKey(KeyCode.T))
{
StartCoroutine(_enumerator(200, 20, 20));
}
}
/// <summary>
/// 简单的对象池管理gameObjects,
/// </summary>
/// <param name="creatCountOnce">一次创建多少个</param>
/// <param name="poolThreshold">对象池使用之前的gameObject的阈值</param>
/// <param name="poolSize">对象池的最大容积</param>
/// <returns>null</returns>
IEnumerator _enumerator(int creatCountOnce, int poolThreshold, int poolSize)
{
//TODO:添加一些对于参数的判定
//endTodo
var toxiccount = creatCountOnce;//每次创建creatCountOnce个
if (gameObjectsPool.Count < poolSize)//池子的最大容积为poolSize个,小于poolSize创建,
{
for (int i = 0; i < toxiccount; i++)//创建模型
{
var toxicmodel = Random.Range(0, goModelList.Count);//在模型的list里随机挑选一个
GameObject goToxic = GameObject.Instantiate(goModelList[toxicmodel], goModelParent.transform);//创建
var posShiftX = Random.Range(0, 200) > 100 ? Random.Range(0, 10) : -Random.Range(0, 10);//X轴偏移
var posShiftZ = Random.Range(0, 200) > 100 ? Random.Range(0, 10) : -Random.Range(0, 10);//Z轴偏移
goToxic.transform.position = new Vector3(
toxicBornTransformList[i].position.x + posShiftX,
toxicBornTransformList[i].position.y,
toxicBornTransformList[i].position.z + posShiftZ);//位置差异化
gameObjectsPool.Add(goToxic);//将对象添加到池中
}
}
else//大于poolSize就把池子中的前poolThreshold个当成最新的
{
for (int i = 0; i < poolThreshold; i++)//使用池中的前poolThreshold个
{
var posShiftX = Random.Range(0, 200) > 100 ? Random.Range(0, 10) : -Random.Range(0, 10);
var posShiftZ = Random.Range(0, 200) > 100 ? Random.Range(0, 10) : -Random.Range(0, 10);//Z轴偏移
gameObjectsPool[i].transform.position = new Vector3(
toxicBornTransformList[i].position.x + posShiftX,
toxicBornTransformList[i].position.y,
toxicBornTransformList[i].position.z + posShiftZ);//位置差异化
var go = gameObjectsPool[i];
gameObjectsPool.Remove(gameObjectsPool[i]);
gameObjectsPool.Add(go);//将对象放到最后去
}
}
yield return null;
}
```