打包资源
在unity中,给预制体、材质球等添加bundleId
接着添加一个脚本,放在Editor文件夹下,编写如下
using UnityEngine;
using System.Collections;
using UnityEditor;
public class CreateAssetBundle {
[MenuItem("Assets/Build AssetBundle")]
static void BuildAllAssetBundle()
{
//打包到的路径 路径需存在
BuildPipeline.BuildAssetBundles("AssetBundles");
}
}
下载并记载AssetBundle,将如下脚本挂载到物体上
using UnityEngine;
using System.Collections;
public class LoadAssetBundle : MonoBehaviour {
//注意读取打包的文件需要加file:// windows下拷贝的路径需要改写斜杠
//file://C:/Users/Administrator/Desktop/assetsbundle/AssetBundleTest/AssetBundles/player_assetbundle
public string url;
//需要下载的 打包前资源的名字
public string assetname;
IEnumerator Start()
{
//自动释放内存 也可用www.LoadFromCacheOrDownload 具体请参照官方文档
using(WWW www=new WWW(url))
{
yield return www;
if(www.error!=null)
{
Debug.LogError("网络错误");
}
else
{
AssetBundle bundle=www.assetBundle;
Object obj=bundle.LoadAsset(assetname);
Instantiate(obj);
//false为释放已经加载过的资源 true为释放全部资源
bundle.Unload(false);
}
}
}
}