weijia_yu
weijia_yu

Reputation: 1015

Unity3D how does AssetBundle cache work?

I am kinda confused about:

After downloading an assetbundle at the first time, how Unity knows I have already downloaded it and directly load from cache(disk) at the second time?

Does it use url to mapping to local storage? If in that case, if I update my assetbundle on the server using the same name, at the second time, it will still be loading from cache since the url doesn't change?

Sample code:

UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.GetAssetBundle(uri, 0);
yield return request.Send();
//only download at the first time, at the second time, it can be loaded from cache
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
GameObject cube = bundle.LoadAsset<GameObject>("Cube");

Upvotes: 1

Views: 5135

Answers (1)

isgoed
isgoed

Reputation: 772

To have caching;

Instead of calling:

UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.GetAssetBundle(uri, 0);

You must call GetAssetBundle with a version number:

UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.GetAssetBundle(uri, 1, 0);

See documentation here: https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.GetAssetBundle.html

You can also implement this with a call to new DownloadHandlerAssetBundle(string url, uint version, uint crc);. See sample code here: https://docs.unity3d.com/ScriptReference/Networking.DownloadHandlerAssetBundle-ctor.html And documentation here: https://docs.unity3d.com/ScriptReference/Networking.DownloadHandlerAssetBundle-ctor.html

Note that when you use caching, the request.responseCode will no longer be value 200 (success), but will be 0, when the data is retrieved from cache!

Upvotes: 2

Related Questions