Load/Unload Assets dynamically

chetan rane picture chetan rane · Feb 25, 2013 · Viewed 16.6k times · Source

i have to manage my RAM so want to load/unload all my ngui pages on the fly. For that i have created AssetBundle with prefabs and i'll kept those AssetBundles in my apk

What is the way to load/unload them on adroid device.

I roughly know about AssetBundle.CreateFromMemory, but unable to implement it

I am thinking in right way or missing something .

any help/??

Answer

Joetjah picture Joetjah · Feb 25, 2013

I think you are in the right way. Unity supports Resource Folders in the project to allow content to be supplied in the main game file yet not be loaded until requested. In Unity Pro, Unity iOS Pro(formerly called 'iOS Advanced') and Unity Android Pro(formerly called 'Android Advanced'), you can also create Asset Bundles. These are files completely separate from the main game file which contain assets to be accessed by the game on demand from a file or URL.

An Asset Bundle is an external collection of assets. You can have many Asset Bundles and therefore many different external collections of assets. These files exist outside of the built Unity player, usually sitting on a web server for end-users to access dynamically.

To build an Asset Bundle, you call BuildPipeline.BuildAssetBundle() from inside an Editor script. In the arguments, you specify an array of Objects to be included in the built file, along with some other options. This will build a file that you can later load dynamically in the runtime by using AssetBundle.Load().

You can unload resources of an AssetBundle by calling AssetBundle.Unload(). If you pass true for the unloadAllLoadedObjects parameter, both the objects held internally by the AssetBundle and the ones loaded from the AssetBundle using AssetBundle.Load() will be destroyed and memory used by the bundle will be released.

Sometimes you may prefer to load an AssetBundle, instantiate the objects desired and release the memory used up by the bundle while keeping the objects around. The benefit is that you free up memory for other tasks, for instance loading another AssetBundle. In this scenario you would pass false as the parameter. After the bundle is destroyed you will not be able to load objects from it any more.

If you want to destroy scene objects loaded using Resources.Load() prior to loading another level, call Object.Destroy() on them. To release assets, use Resources.UnloadUnusedAssets().

Read the whole story in Unity docs.