Download AssetBundle in hard disk
Right now, it seems UnityWebRequest.GetAssetBundle
download asset to RAM and load. Is there anyway to download to hard disk to load?
Solution 1:
This is not really complicated. Handle it like a normal file you would download from the internet but save it with the ".unity3d" extension.
1.Download the AssetBundle
as a normal file by making a request with UnityWebRequest
.
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
2.Retrieve the byte array data with DownloadHandler.data
then save it to Application.persistentDataPath/yourfolder/filename.unity3d
. Make sure that the extension is ".unity3d".
File.WriteAllBytes(handle.data, data);
That's it.
3.To load the data, use AssetBundle.LoadFromFile
or AssetBundle.LoadFromFileAsync
:
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
If still confused, here is what the thing should look like. You may need to make some modification:
Download and Save:
IEnumerator downloadAsset()
{
string url = "http://url.net/YourAsset.unity3d";
UnityWebRequest www = UnityWebRequest.Get(url);
DownloadHandler handle = www.downloadHandler;
//Send Request and wait
yield return www.Send();
if (www.isError)
{
UnityEngine.Debug.Log("Error while Downloading Data: " + www.error);
}
else
{
UnityEngine.Debug.Log("Success");
//handle.data
//Construct path to save it
string dataFileName = "WaterVehicles";
string tempPath = Path.Combine(Application.persistentDataPath, "AssetData");
tempPath = Path.Combine(tempPath, dataFileName + ".unity3d");
//Save
save(handle.data, tempPath);
}
}
void save(byte[] data, string path)
{
//Create the Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
try
{
File.WriteAllBytes(path, data);
Debug.Log("Saved Data to: " + path.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Save Data to: " + path.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
Load:
IEnumerable LoadObject(string path)
{
AssetBundleCreateRequest bundle = AssetBundle.LoadFromFileAsync(path);
yield return bundle;
AssetBundle myLoadedAssetBundle = bundle.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
AssetBundleRequest request = myLoadedAssetBundle.LoadAssetAsync<GameObject>("boat");
yield return request;
GameObject obj = request.asset as GameObject;
obj.transform.position = new Vector3(0.08f, -2.345f, 297.54f);
obj.transform.Rotate(350.41f, 400f, 20f);
obj.transform.localScale = new Vector3(1.0518f, 0.998f, 1.1793f);
Instantiate(obj);
myLoadedAssetBundle.Unload(false);
}