-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathAssetBundleLoader.cs
More file actions
107 lines (89 loc) · 3.28 KB
/
AssetBundleLoader.cs
File metadata and controls
107 lines (89 loc) · 3.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
namespace UnityLibrary
{
public class AssetBundleLoader : MonoBehaviour
{
public string assetBundleURL = "http://localhost/bundle";
private string bundleName = "bundle";
void Start()
{
StartCoroutine(DownloadAndCache(assetBundleURL));
}
IEnumerator DownloadAndCache(string bundleURL, string assetName = "")
{
while (!Caching.ready)
{
yield return null;
}
// Clear cache for previous versions of the asset bundle
Caching.ClearOtherCachedVersions(bundleName, Hash128.Parse("0"));
UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest?r=" + (Random.value * 9999999));
Debug.Log("Loading manifest: " + bundleURL + ".manifest");
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.LogError("www error: " + www.error);
www.Dispose();
www = null;
yield break;
}
Hash128 hashString = default(Hash128);
if (www.downloadHandler.text.Contains("ManifestFileVersion"))
{
var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());
if (hashString.isValid)
{
if (Caching.IsVersionCached(bundleURL, hashString))
{
Debug.Log("Bundle with this hash is already cached!");
}
else
{
Debug.Log("No cached version found for this hash..");
}
}
else
{
Debug.LogError("Invalid hash: " + hashString);
yield break;
}
}
else
{
Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
yield break;
}
www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + (Random.value * 9999999), hashString, 0);
yield return www.SendWebRequest();
if (www.error != null)
{
Debug.LogError("www error: " + www.error);
www.Dispose();
www = null;
yield break;
}
AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
GameObject bundlePrefab = null;
if (assetName == "")
{
bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
}
else
{
bundlePrefab = (GameObject)bundle.LoadAsset(assetName);
}
if (bundlePrefab != null)
{
Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity);
}
www.Dispose();
www = null;
Resources.UnloadUnusedAssets();
bundle.Unload(false);
bundle = null;
}
}
}