Unity5.5 AssetBundle用法-面向Android平台(1)

一个AssetBundle在unity5.5中使用的例子,目标平台是android

以一个胶囊体为例:

1、创建prefab。简单一点,把胶囊体直接放在Assets根目录下:

2、为prefab命名。本例中命名为cab:

3、在Assets同级路径下创建AssetBundle根目录。本例中目录名称为“AssetBundles”。

4、编写生成AssetBundle的代码。代码如下,在Assets目录下创建Editor文件夹,放在里面:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class BuildAssetBundle{

	[MenuItem("AssetBundle/Build All AssetBundle")]
	static void BuildAllAssetBundle() {

		string path = "AssetBundles";//相对目录,和Asset同级
		if (!Directory.Exists(path)) {
			Directory.CreateDirectory(path);
		}

		BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, BuildTarget.Android);
		//None使用LZMA算法压缩,被压缩的包相比LZ4更多,但是解压时间更久,加载时间更久,解压是必须整体解压
		//ChunkBasedCompressor LZ4压缩 可以指定加载具体的资源而无需全部解压
	}
}

5、Unity主界面中,点击“AssetBundle/Build All AssetBundle”,生成AssetBundle文件,打开如下:

 

6、将AssetBundles文件夹拷贝至你网站的根目录下:

7、加载资源,代码如下:

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class MyBehaviour : MonoBehaviour
{
	void Start()
	{
		
	}
	void OnGUI(){
		if (GUILayout.Button ("begin",GUILayout.Width(500),GUILayout.Height(300))) {
			StartCoroutine(WebRequest());
		}
	}	

	IEnumerator WebRequest() {
		string cubeURL = "http://XXX.com/yourweb/AssetBundles/cab";

		UnityWebRequest request = UnityWebRequest.GetAssetBundle(cubeURL);
		yield return request.Send();//发送http请求

		if(string.IsNullOrEmpty(request.error)){//没有错误
			AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
			GameObject cubeWall = ab.LoadAsset<GameObject>("Capsule");//获取prefab
			Instantiate(cubeWall, Vector3.zero, Quaternion.identity);//实例化prefab
		}else{
			yield break;
		}
	}
}

8、将该脚本绑定在场景中的对象上,执行,点击“begin”,你会发现可以正常加载资源并在零点创建了一个胶囊体对象。

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值