1. 程式人生 > >Unity資源載入與釋放

Unity資源載入與釋放

參考資源

http://www.cnblogs.com/freebird92/archive/2013/03/12/2955888.html
http://www.taidous.com/bbs/article-445-1.html

AssetBundle 與 Resources的區別

Resources相當於Unity一個預設的AssetBundle。
AssetBundle可以在使用時動態載入。
Resources.load();在沒有第一次Instantiate之前沒有完全載入Asset資源。所以相對AssetBundle去例項一個資源,Resources會在第一次Instantiate時出現卡頓現象。

AssetBundle 載入與釋放

AssetBundle的載入方式有:AssetBundle.LoadFromFile(“”); AssetBundle.LoadFromMemorty(byte[]);及WWW方式。
AssetBunddle.LoadFromFile(“”);只有在standalone上可以使用。WWW在載入AssetBundle時,會在內部建立assetBundle例項。
當AssetBundle被載入到記憶體後,其實記憶體中只有AssetBundle檔案的映象記憶體。//todo 該映象檔案是AssetBundle原檔案大小?
當需要具體某個Prefab等資源時,使用assetbundle.Load(“”);載入具體資源。此時記憶體中會存在此資源的 GameObject、shaders、材質、貼圖等記憶體。當具體Instantiate一個資源時,會對此資源的Asset資源進行clone+引用操作。Clone的資源包括GameObject、Tranform。引用的資源包括Texture、TerrainData、Shader。引用與Clone同時存在的包括 Mesh、material、PhysicMaterial、noxss。引用的資源只是指標的指向。Clone的會重新生成新的記憶體。
根據AssetBundle資源的載入方式,當資源釋放時,如果只是Destroy,只會釋放生成這個資源時Clone的那部分記憶體。assetBundle.Load(“”);載入的Asset記憶體沒有被釋放,AssetBundle的映象記憶體也沒有被釋放。所以如果在該資源被銷燬時需要使用Resources.UnloadUnuseAssets();去釋放沒有被使用的Asset資源記憶體。如果該AssetBundle不會被再使用可以使用AssetBundle.Unload(true)銷燬記憶體。AssetBundle(true);代表銷燬該AssetBundle映象記憶體及所載入的Asset記憶體。引數為false時,代表只銷毀映象記憶體。
下面的圖片可以更形象的理解AssetBundle的載入與釋放。

備註

當場景在切換時,Unity 會自動 把託管的記憶體釋放,這其中包括Asset記憶體、Instantiate記憶體。但不會被釋放的是AssetBundle映象記憶體。
assetBundle.Load如果多次載入相同的資源,除第一次,其它都會返回第一次的物件。