Unity AssetBundle打包场景并加载

版权声明:转载请注明出处。 https://blog.csdn.net/QWBin/article/details/83210612

1.首先我们创建俩场景用于切换。

2.编辑俩脚本。

脚本1(放入Editor文件夹):可以在unity菜单栏的Assets下方找到Build AssetBundle MyScene。如下图:

CreatAssetsBundle:

using UnityEngine;
using System.Collections;
using UnityEditor;

public class CreatAssetsBundle : Editor
{

    // 打包unity场景文件
    [MenuItem("Assets/Build AssetBundle MyScene")]
    static void MyBuild()
    {
        // 需要打包的场景名字
        string[] path = { "Assets/loadScene.unity" };
        BuildPipeline.BuildPlayer(path, Application.dataPath + "/MyScene.unity3d", BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);
        // 刷新,可以直接在Unity工程中看见打包后的文件
        AssetDatabase.Refresh();

    }

}

脚本2(用于下载AssetsBundle打包的场景):

LoadScene:

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class LoadScene : MonoBehaviour
{

    private string url;
    private string assetname;

    void Start()
    {
        // 下载压缩包,写出具体的名字
        url = "file://" + Application.dataPath + "/MyScene.unity3d";
        assetname = "SampleScene";
        StartCoroutine(Download());
    }

    IEnumerator Download()
    {

        WWW www = new WWW(url);
        // Debug.LogError(url);
        yield return www;
        if (www.error != null)
        {
            Debug.Log("下载失败");
        }
        //else//第一种加载方法  需要把场景拖进buildsetting
        //{
        //    AssetBundle bundle = www.assetBundle;
        //    SceneManager.LoadScene(0);
        //    print("跳转场景");
        //    // AssetBundle.Unload(false),释放AssetBundle文件内存镜像,不销毁Load创建的Assets对象
        //    // AssetBundle.Unload(true),释放AssetBundle文件内存镜像同时销毁所有已经Load的Assets内存镜像
        //    bundle.Unload(false);
        //}
        else//第二种方法 直接加载
        {
            WWW download = WWW.LoadFromCacheOrDownload("file://" + Application.dataPath + "/MyScene.unity3d", 1);
            yield return download;
            var bundle = download.assetBundle;
            SceneManager.LoadScene(assetname);
        }

        // 中断正在加载过程中的WWW
        www.Dispose();
    }

}

准备工作:

先后先点击“Build AssetBundle MyScene”

点击:

好了  大家可以试试  因为不同的平台是不一样的  大家可以参考下:

 public static readonly string PathURL =
#if UNITY_ANDROID
            "jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
            Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
        "file://" + Application.dataPath + "/StreamingAssets/";
#else
            string.Empty;
#endif
    public string PathURL = "file://" + Application.dataPath + "/StreamingAssets/";

然后注意StreamingAssets文件夹 这是一个只读的文件,而其加载不压缩。因为我这里发布的是PC端的  所以可以直接用。大家用的话还是注意点。

猜你喜欢

转载自blog.csdn.net/QWBin/article/details/83210612