資源描述:
《Unity3D游戲開(kāi)發(fā)之對(duì)象池技術(shù)(優(yōu)化)》由會(huì)員上傳分享,免費(fèi)在線(xiàn)閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫(kù)。
1、Unity3D游戲開(kāi)發(fā)之對(duì)象池技術(shù)(優(yōu)化)我們?cè)谧鲰?xiàng)目的時(shí)候,如果同一個(gè)物體要用到好多次,我們就不要再用實(shí)例化了,因?yàn)槊看蝿?chuàng)建一個(gè)新物體是很消耗資源的,引用對(duì)象池技術(shù),顧名思義,把所有要用到的對(duì)象在初始化的時(shí)候都扔到這個(gè)池子里,想用的時(shí)候拿出來(lái)用,不想用的時(shí)候放回去,這樣會(huì)大大節(jié)省資源,我在狗刨上看到一個(gè)寫(xiě)對(duì)象池不錯(cuò)的code,拿來(lái)分享一下。??這個(gè)腳本非常簡(jiǎn)單,但它可以通過(guò)大量減少實(shí)例化所帶來(lái)的開(kāi)銷(xiāo)使我的iOS游戲得到很大的性能提升。??1.把腳本ObjectPool.cs鏈接到一個(gè)GameObject上。2.在物體預(yù)設(shè)數(shù)組中設(shè)置你想
2、要放到池中并重復(fù)利用的預(yù)設(shè)物體。3.在緩沖數(shù)組中,指定你希望每個(gè)物體在游戲開(kāi)始時(shí)被實(shí)例化的數(shù)量,這樣在開(kāi)始的時(shí)候你就有了池對(duì)象。4.在你的游戲中調(diào)用ObjectPool.instance.GetObjectForType(objectType,onlyPooled)來(lái)使用它。objectType寫(xiě)你想生成的預(yù)設(shè)的名字、并為onlyPooled指定布爾值,如果返回真,它將返回你已經(jīng)放到池中的對(duì)象;如果返回假,它將實(shí)例化一個(gè)全新的對(duì)象。(如果你想限制被池對(duì)象的數(shù)量,那么設(shè)定為真,這樣做非常有用,尤其是在需要限制同時(shí)播放特效的數(shù)量的時(shí)候)。文
3、章出處【狗刨學(xué)習(xí)網(wǎng)】5.確保你從池中調(diào)用的對(duì)象知道當(dāng)它被刪除時(shí)需要返回到池中。1.??2.3.usingUnityEngine;4.usingSystem.Collections;5.usingSystem.Collections.Generic;6.7.publicclassObjectPool:MonoBehaviour8.{9.10.??publicstaticObjectPoolinstance;11.12.??///13.??///Theobjectprefabswhichthepoolcanhandle.1
4、4.??///15.??publicGameObject[]objectPrefabs;1.2.??///3.??///Thepooledobjectscurrentlyavailable.4.??///5.??publicList[]pooledObjects;6.7.??///8.??///Theamountofobjectsofeachtypetobuffer.9.??///10.??publicint[]amo
5、untToBuffer;11.12.??publicintdefaultBufferAmount=3;13.14.??///15.??///Thecontainerobjectthatwewillkeepunusedpooledobjectssowedontcloguptheeditorwithobjects.16.??///17.??protectedGameObjectcontainerObject;18.19.??voidAwake()20.??{21.??????instance=this;
6、22.??}23.24.??//Usethisforinitialization25.??voidStart()26.??{27.??????containerObject=newGameObject("ObjectPool");28.29.??????//Loopthroughtheobjectprefabsandmakeanewlistforeachone.1.??????//Wedothisbecausethepoolcanonlysupportprefabssettoitintheeditor,2.??????//sowecan
7、assumethelistsofpooledobjectsareinthesameorderasobjectprefabsinthearray3.??????pooledObjects=newList[objectPrefabs.Length];4.5.??????inti=0;6.??????foreach(GameObjectobjectPrefabinobjectPrefabs)7.??????{8.????????pooledObjects[i]=newList();?9.10.?
8、???????intbufferAmount;11.12.????????if(i