[Unity3D]AssetBundle加载和卸载学习笔记

自学笔记,仅供参考。



		string path = "AssetBundles/cubewall.unity3d";

		//本地同步加载
		AssetBundle ab = AssetBundle.LoadFromFile ("AssetBundles/share.unity3d"); //要先加载所依赖的资源
		AssetBundle ab2 = AssetBundle.LoadFromFile (path);
		//本地异步加载,需要协程
		AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync (path);
		yield return request;
		AssetBundle ab = request.assetBundle;

		//内存异步加载,需要协程
		AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync (File.ReadAllBytes (path));
		yield return request;
		AssetBundle ab = request.assetBundle;
		//内存同步加载
		AssetBundle ab = AssetBundle.LoadFromMemory (File.ReadAllBytes (path));

		//通过WWW加载,已被Unity弃用
		while (!Caching.ready)
			yield return null;
		WWW www = WWW.LoadFromCacheOrDownload (@"file:///G:\unity\Project\AssetBundleLearn\AssetBundles\CubeWall.unity3d",1);
		WWW www = WWW.LoadFromCacheOrDownload (@"http://localhost/AssetBundles/CubeWall.unity3d",1);
		yield return www;
		if (!string.IsNullOrEmpty (www.error))
		{
			Debug.Log (www.error);
			yield break;
		}
		AssetBundle ab = www.assetBundle;

		//使用UnityWbeRequest加载
		string uri = @"file:///G:\unity\Project\AssetBundleLearn\AssetBundles\CubeWall.unity3d";
		//服务器端地址
//		string uri = @"http://localhost/AssetBundles/CubeWall.unity3d";
		UnityWebRequest request = UnityWebRequest.GetAssetBundle (uri);
		yield return request.SendWebRequest ();
		//两种方法
//		AssetBundle ab = DownloadHandlerAssetBundle.GetContent (request);
		AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

		//实例化资源
		GameObject wallPrefab = ab.LoadAsset ("CubeWall");
		Instantiate (wallPrefab);

                //通过Manifest加载依赖资源
		AssetBundle manifestAB = AssetBundle.LoadFromFile ("AssetBundles/AssetBundles");
		AssetBundleManifest manifest = manifestAB.LoadAsset ("AssetBundleManifest");

		string[] strs = manifest.GetAllDependencies ("cubewall.unity3d");
		foreach (string name in strs)
		{
			print (name);
			AssetBundle.LoadFromFile ("AssetBundles/" + name);
		}
		foreach (string name in manifest.GetAllAssetBundles())
			print (name);

你可能感兴趣的:(Unity3D)