美文网首页
AssetBundle的打包及四种加载资源方式

AssetBundle的打包及四种加载资源方式

作者: 青青子衿_悠悠我鑫 | 来源:发表于2018-03-01 14:39 被阅读0次

一.AssetBundle的打包(C#)

需要将脚本放在Editor文件夹内,具体代码如下:

usingUnityEditor;

usingSystem.IO;

public class CreateAssetBundles{

    [MenuItem("Build AssetBundles")]

    static void BuildAssetBundles()

    {

        //定义文件夹名字

        string dir="AssetBundles";

        //若文件夹不存在,则创建

        if(!Directory.Exists(dir))

        {

            Directory.CreateDirectory(dir);

        }

        //资源打包,路径,压缩方式,平台

        BuildPipeline.BuildAssetBundles(dir,BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows64);

    }

}

二.AssetBundle的加载(C#)

1.

1.1异步加载--用IEnumerator

string path ="AssetBundles/cube";

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

yield return request; 

AssetBundle ab = request.assetBundle;

//使用里面的资源

GameObject cubePrefab = ab.LoadAsset("Cube");

Instantiate(cubePrefab);

1.2同步加载--不使用协程

string path ="AssetBundles/cube";

AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));

//使用里面的资源

GameObject cubePrefab = ab.LoadAsset("Cube");

Instantiate(cubePrefab);

2.本地加载LoadFromFile--用IEnumerator

string path ="AssetBundles/cube";

AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);

yield return request;

AssetBundle ab = request.assetBundle;

//使用里面的资源

GameObject cubePrefab = ab.LoadAsset("Cube");

Instantiate(cubePrefab);

3.从服务器加载 WWW

string url = "http://localhost/AssetBundles/cube";

//是否准备好

while (Caching.ready == false)

{

    yield return null;

}

WWW www = WWW.LoadFromCacheOrDownload(url, 1);

yield return www;

if (string.IsNullOrEmpty(www.error) == false)

{

    Debug.Log("错误信息为:"+www.error);

    yield break;

}

AssetBundle ab = www.assetBundle;

if (ab == null)

{

    Debug.LogError(GetType() + "/LoadFromAB()/www下载错误,请检查URL:" + url + "错误信息:" + www.error);

}

//使用里面的资源

GameObject cubePrefab = ab.LoadAsset("Cube");

Instantiate(cubePrefab);

4.从服务器端下载 UnityWebRequest(新版Unity使用)

string url = "http://localhost/AssetBundles/cube.unity3d";

UnityWebRequest request= UnityWebRequest.GetAssetBundle(url);

yield return request.Send();

//AssetBundle ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);

//加载manifest

AssetBundle manifestAB = AssetBundle.LoadFromFile("AssetBundles/AssetBundles"); 

AssetBundleManifest manifest = manifestAB.LoadAsset("AssetBundleManifest");

//加载出cube所依赖的包

string[] strs = manifest.GetAllDependencies("cube");

foreach(string name in strs)       

{            

    AssetBundle.LoadFromFile("AssetBundles/"+ name);        

}

//使用里面的资源

GameObject cubePrefab = ab.LoadAsset("Cube");        

Instantiate(cubePrefab);

相关文章

网友评论

      本文标题:AssetBundle的打包及四种加载资源方式

      本文链接:https://www.haomeiwen.com/subject/wkmgxftx.html