Unity Assetbundle Scene packaging and loading

https://blog.csdn.net/qq_15697801/article/details/80003488

Pack

using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

public class AssetBundleTest : MonoBehaviour
{

    [MenuItem("Custom Editor/AssetBundle/Bundle Scene")]
    static void CreateSceneALL()
    {
        //Clear the cache
        Caching.CleanCache();
        List<BundleData> strmes = GetSelectionFile(".unity");
        Debug.Log(strmes.Count);
        if (strmes.Count <= 0)
            return;
        string Path=string.Empty;
        string filepath = PlayerPrefs.GetString("Path");
        foreach (var item in strmes)
        {
            //Method to get the path selected by the user, you can open the save panel (recommended)
            if(string.IsNullOrEmpty(Path))
            {
                if(string.IsNullOrEmpty(filepath))
                {
                    Path = EditorUtility.SaveFilePanel("Save Resource", "SS", "" + item.Name, "unity3d");
                    filepath = Path.Substring(0, Path.LastIndexOf('/'));
                }
                else
                {
                    Path = filepath + "/" + item.Name + ".unity3d";
                }
                PlayerPrefs.SetString("Path", filepath);
            }
            //Another way to obtain the path selected by the user. By default, the packaged files are placed in the Assets directory.
            //string Path = Application.dataPath + "/MyScene.unity3d";
            //The selected object to save
            string[] levels = {item.LevelsPath};
            //Package scene
            BuildPipeline.BuildPlayer(levels, Path, BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);
        }
        // Refresh, you can see the packaged files directly in the Unity project
        AssetDatabase.Refresh();
        if(!string.IsNullOrEmpty(filepath))
        {
            System.Diagnostics.Process.Start(filepath);
            Debug.Log("Bundle Success!!!");
        }
    }
    [MenuItem("Custom Editor/AssetBundle/Clear FilePath")]
    static public void ClearFilePath()
    {
        PlayerPrefs.DeleteKey("Path");
        Debug.Log("Default address cleared successfully!" + PlayerPrefs.GetString("Path"));
    }
    //Get the file selected by the mouse and only return the file name and suffix
    static public string[] GetSelectionFile()
    {
        //SelectionMode.Unfiltered returns the entire selection.
        //SelectionMode.TopLevel returns only the transformation for the topmost selection; other selected sub-objects will be filtered out.
        //SelectionMode.Deep Returns the selection and all selected subtransformations.
        //SelectionMode.ExcludePrefab Excludes any prefab from selection.
        //SelectionMode.Editable excludes any objects from being modified.
        //SelectionMode.Assets only returns resource objects in the resource directory.
        //SelectionMode.DeepAssets If the selection includes folders, also includes all assets and subdirectories.
        //SelectionMode.OnlyUserModifiable Only users can modify it? ?
        UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel);

        string[] str = new string[arr.Length];
        for (int i = 0; i < arr.Length; + + i)
        {
            string s = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/')) + "/" + AssetDatabase.GetAssetPath(arr[i]);
            Debug.Log(s);
            str[i] = s.Substring(s.LastIndexOf('/') + 1, s.Length - s.LastIndexOf('/') - 1);
            Debug.Log(str[i]);
        }
        return str;
    }
    //Get the file selected by the mouse, verify the suffix and return the file name
    static public List<BundleData> GetSelectionFile(string suffix)
    {
        UnityEngine.Object[] arr = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.TopLevel);

      // string[] str = new string[arr.Length];
        List<BundleData> liststr = new List<BundleData>();
        for (int i = 0; i < arr.Length; + + i)
        {
            string s = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/')) + "/" + AssetDatabase.GetAssetPath(arr[i]);
            Debug.Log(s);
            var strName = s.Substring(s.LastIndexOf('/') + 1, s.Length - s.LastIndexOf('/') - 1);
            if (strName.EndsWith(suffix)) {
               // var file = AssetDatabase.GetAssetPath(arr[i]);
              // str[i] = GetString(strName, suffix);
               // Debug.Log(str[i]);
                BundleData strdata = new BundleData();
                strdata.AllName = strName;
                strdata.Name = GetString(strName, suffix);
                    strdata.Suffix = suffix;
                strdata.FilePath = s;
                strdata.LevelsPath= AssetDatabase.GetAssetPath(arr[i]);
                liststr.Add(strdata);
            }
        }
        return liststr;
    }
    ///<summary>
    ///Truncate characters before and after (string)
    ///</summary>
    ///<param name="val">Original string</param>
    ///<param name="str">String to be truncated</param>
    ///<param name="all">Is it greedy</param>
    ///<returns></returns>
    private static string GetString(string val, string str, bool all=true)
    {
        return Regex.Replace(val, @"(^(" + str + ")" + (all ? "*" : "") + "|(" + str + ")" + (all ? "*" : " ") + "$)", "");
    }
}
public class BundleData{
    public string AllName;//name with suffix
    public string Name;//name without suffix
    public string Suffix;//suffix
    public string FilePath;//Full path
    public string LevelsPath;//Path within the project
    }

load

/// <summary>
    /// Real scene loading method
    /// </summary>
    /// <returns></returns>
    public IEnumerator LoadReallyScene( string path)
    {
        // path= path.Replace("/","");
        // !isnewload ? (AppDefine.Bundle_Root_Env + GlobalConfig.Instance.SceneName + ".prefab") : (ModelManager.Instance.GetRelativeDirUrl(RelativeDirEnum.Model) + GlobalConfig.Instance.SceneName + ".prefab");
        WWW bundle = new WWW(path);
        yield return bundle;
        if (bundle.error == null)
        {
            AssetBundle ab = bundle.assetBundle; //Load the scene into memory through AssetBundle
            AsyncOperation asy = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); //sceneName cannot be added with a suffix, it is just the scene name
            yield return asy;
            OnSceneLoadEnd(); //Execute callback
        }
        else
        {
            Debug.LogError(bundle.error);
        }

    }