關(guān)于對象池铆农,其實是為了避免重復的對場景中的某個需要大量存在的物體進行銷毀譬挚,創(chuàng)建這樣反復的過程。當然反復的進行銷毀與創(chuàng)建梗夸,這是很耗性能的一個問題。
使用對象池就能很好的避免這樣的問題
這個也是我從公司主程那里學來一個知識點吧号醉,用到了棧這個數(shù)據(jù)結(jié)構(gòu)
記錄一下代碼:
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);
}
}
其實就是反復的進行壓棧與出棧操作反症,然后有一個記錄最多需要多少物體的數(shù),一個記錄生成多少物體的數(shù)畔派,通過對比铅碍,然后進行顯示與隱藏物體。
步驟:
我將這個腳本掛在了場景里的Main Camera身上线椰,然后又寫了一個點擊Cube的函數(shù)(在下面)胞谈,然后運行就OK了,當然別忘記拖動Cube到gameObjectPrefab里
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyGameObject : MonoBehaviour
{
private void OnMouseDown()
{
PoolsController.GetInstacne().DestroyGameObject(this.gameObject);
}
}