打包资源
创建一个物体(cube)
将物体制作成预制体
具体的操作是将物体拖拽至 Project>Assets>Prefabs文件夹内,然后就会直接生成一个预制体。
点击New的按钮可以创建一个新的tag。
点击new可以创建一个后缀。
本次采用 cube的标签,unity3d的后缀。
基本的物体创建与分类完成,现在需要将预制体打包,需要用unity的编辑器模式来完成。新建一个脚本,取名为CreateAssetBundles,去掉继承的mono,using 一下
UnityEditor和 IO。
using UnityEditor;
using System.IO;
public class CreateAssetBundles {
//将本方法放在Assets目录中
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
//创建一条 路径
string dir = "AssetBundles";
//判断该文件夹是否存在于根目录中
if( Directory.Exists(dir)==false)
{
//不存在就新建一个文件夹
Directory.CreateDirectory(dir);
}
//将做好的Assectbundle打包,到新创建的文件夹中
BuildPipeline.BuildAssetBundles(dir,BuildAssetBundleOptions.UncompressedAssetBundle, BuildTarget.StandaloneWindows64);
}
}
因为是编辑器模式,不需要运行该程序的,直接在 目录中寻找该方法。
本地加载通过脚本来实现,最简单的一种是通过路径来加载。
void Start () {
string path = "AssetBundles/myprefab.unity3d";
AssetBundle ab = AssetBundle.LoadFromFile(path);
GameObject wallPrefab = ab.LoadAsset<GameObject>("Cylinder");
Instantiate(wallPrefab);
}
string treepath = "AssetBundles/tree.unity3d";
AssetBundle abs = AssetBundle.LoadFromMemory(File.ReadAllBytes(treepath));
GameObject Prefab = abs.LoadAsset<GameObject>("Tree");
Instantiate(Prefab);
AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
yield return request;
AssetBundle ab = request.assetBundle;
GameObject Prefab = ab.LoadAsset<GameObject>("Tree");
Instantiate(Prefab);
WWW www = WWW.LoadFromCacheOrDownload(@"http://localhost/AssetBundles/cubewall.unity3d", 1);
yield return www;
if ( string.IsNullOrEmpty(www.error)==false )
{
Debug.Log(www.error);yield break ;
}
AssetBundle ab = www.assetBundle;
GameObject Prefab = ab.LoadAsset<GameObject>("Tree");
Instantiate(Prefab);
因为是涉及到WWW此方法适用于服务器网络加载.
使用此方法需要Using UnityEngine.Networking;
此方法同样可以适用于网络和本地的加载
string uri = @"http://www.nuiar.com/company/AssetBundle/cube.unity3d";
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri);
yield return request.SendWebRequest();
AssetBundle abd = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
print(abd);