AssetBundle的本地打包与加载,服务器加载

打包资源

创建一个物体(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);

    }

}

因为是编辑器模式,不需要运行该程序的,直接在 目录中寻找该方法。

  1. 资源加载
  1. 本地加载

本地加载通过脚本来实现,最简单的一种是通过路径来加载。

    void Start () {

        string path = "AssetBundles/myprefab.unity3d";

        AssetBundle ab = AssetBundle.LoadFromFile(path);

        GameObject wallPrefab = ab.LoadAsset<GameObject>("Cylinder");

        Instantiate(wallPrefab);

}

  1. LoadFromMemory 

        string treepath = "AssetBundles/tree.unity3d";      

AssetBundle abs = AssetBundle.LoadFromMemory(File.ReadAllBytes(treepath));

        GameObject Prefab = abs.LoadAsset<GameObject>("Tree");

         Instantiate(Prefab);

  1. LoadFromMemoryAsync

       AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));

       yield return request;

AssetBundle ab = request.assetBundle;

    GameObject Prefab = ab.LoadAsset<GameObject>("Tree");

         Instantiate(Prefab);

  1. WWW

        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此方法适用于服务器网络加载.

  1.  UnityWebRequest

使用此方法需要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);

 

 

 



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值