关于对象池,其实是为了避免重复的对场景中的某个需要大量存在的物体进行销毁,创建这样反复的过程。当然反复的进行销毁与创建,这是很耗性能的一个问题。
使用对象池就能很好的避免这样的问题
这个也是我从公司主程那里学来一个知识点吧,用到了栈这个数据结构
记录一下代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolsController : MonoBehaviour {
public GameObject gameObjectPrefab;
public int maxGameObjectCounts=100;
[HideInInspector]
public int gameObjectCount;
private Stack gameObjcetPool = new Stack();
private int gameObjectName;
private Transform gameObjectParent;
private static PoolsController _instance;
public static PoolsController GetInstacne()
{
if(_instance==null)
{
_instance = GameObject.Find("Main Camera").GetComponent<PoolsController>();
}
return _instance;
}
private void Start()
{
if(GameObject.Find("gameObjectParent")!=null)
{
gameObjectParent = GameObject.Find("gameObjectParent").transform;
}
else
{
Debug.LogError("Don't find gameObjcetParent");
}
gameObjectName = 0;
gameObjectCount = 0;
}
// Update is called once per frame
void Update () {
PoolManager();
}
void PoolManager()
{
if(gameObjectCount<maxGameObjectCounts)
{
CreateGameObject(RandomPosition(), RandomScale());
++gameObjectCount;
}
}
private GameObject CreateGameObject(Vector3 randomPosition,float randomScale)
{
GameObject obj = null;
if(gameObjcetPool.Count>0)
{
obj = gameObjcetPool.Pop() as GameObject;
obj.gameObject.SetActive(true);
}
else
{
GameObject createObj = Instantiate(gameObjectPrefab);
createObj.transform.parent = gameObjectParent;
obj = createObj;
obj.AddComponent<DestroyGameObject>();
obj.name = gameObjectName.ToString();
gameObjectName++;
}
obj.transform.position = randomPosition;
obj.transform.localScale = new Vector3(randomScale, randomScale, randomScale);
return obj;
}
private Vector3 RandomPosition()
{
return new Vector3(Random.Range(0.0f, 5.0f), Random.Range(0.0f, 5.0f), Random.Range(0.0f, 5.0f));
}
private float RandomScale()
{
return Random.Range(0.0f, 1.0f);
}
public void DestroyGameObject(GameObject needDestroyObj)
{
needDestroyObj.SetActive(false);
gameObjcetPool.Push(needDestroyObj);
gameObjectCount--;
Debug.Log("gameObjectCount in DestroyGameObjectFunc:" + gameObjectCount);
}
}
其实就是反复的进行压栈与出栈操作,然后有一个记录最多需要多少物体的数,一个记录生成多少物体的数,通过对比,然后进行显示与隐藏物体。
步骤:
我将这个脚本挂在了场景里的Main Camera身上,然后又写了一个点击Cube的函数(在下面),然后运行就OK了,当然别忘记拖动Cube到gameObjectPrefab里
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyGameObject : MonoBehaviour
{
private void OnMouseDown()
{
PoolsController.GetInstacne().DestroyGameObject(this.gameObject);
}
}