LoginSignup
76
65

アセットバンドルの作り方・ロード方法の色々メモ(ver5.4.0f3・ver5.3.0f4・ver5.0.1f・ver4.6.2)

Last updated at Posted at 2015-03-27

【2016/08/25追記】

iOS側Unity5.4.0f3 によるシーンアセットバンドルのロード処理(StreamingAssetsフォルダを使用)

Xcodeで実行するときの注意点として、
iOSのBuildSettings ->OtherSettings->Strip EngineCodeのチェックを外す。

こうしないとAnimatorControllerがエラーを起こして再生されない。

下記URLにstrippinglevelAnimatorControllerに関してそれっぽいことが書いてある
http://forum.unity3d.com/threads/could-not-produce-class-with-id-91-ios.267548/
http://docs.unity3d.com/Manual/webgl-building.html

Unity5.4.0f3 によるシーンアセットバンドルのロード処理の備忘録

    public List<Texture2D> TextureLists = new List<Texture2D> ();
    public List<Material> MaterialLists = new List<Material> ();
    public List<GameObject> GameObjectLists = new List<GameObject> ();
    List<string> listMaster = new List<string> ();

    public void TestLoc1_BundleLoadStreamingAssets ()
    {

        #if UNITY_IPHONE
        AssetBundle manifestBundle = AssetBundle.LoadFromFile (Application.dataPath + "/Raw/iOS");
        #elif UNITY_EDITOR
        AssetBundle manifestBundle = AssetBundle.LoadFromFile (Application.streamingAssetsPath + "/iOS");
        #endif
        AssetBundleManifest manifest = manifestBundle.LoadAsset ("AssetBundleManifest") as AssetBundleManifest;
        List<string> ListA = new List<string> ();

        // シーンに必要なもの
        ListA.Add (フォルダアセットバンドル名1);
        ListA.Add (フォルダアセットバンドル名2);
        ListA.Add (フォルダアセットバンドル名3);
        ListA.Add (フォルダアセットバンドル名4);
        ListA.Add (フォルダアセットバンドル名5);
        ListA.Add (フォルダアセットバンドル名6);

        // シーン        
        ListA.Add (シーンのアセットバンドル名);

        listMaster.AddRange (ListA);

        bool noDependenceFlg = false;

        while ( noDependenceFlg == false ) {
            List<string> ListB = new List<string> ();
            // 1段階ネストされた依存関係リストを作成
            foreach (string bundlename in ListA) {
                // 直接の依存関係リストを取得
                string[] dependenceArray = manifest.GetDirectDependencies (bundlename);

                ListB.AddRange (dependenceArray);
            }

            // 重複排除
            ListB = ListB.Distinct ().ToList ();

            ListA.Sort ();
            ListB.Sort ();

            if ( (ListB.Count == 0) || (ListA.SequenceEqual (ListB) == true) ) {
                noDependenceFlg = true;
            } else {
                // 1段階ネストされた依存関係リストを作成
                foreach (string dependenceBundle in ListB) {
                    // すでに存在すれば削除して最後尾に追加
                    if ( listMaster.Contains (dependenceBundle) == true ) {
                        listMaster.Remove (dependenceBundle);
                    }
                    listMaster.Add (dependenceBundle);
                }
                ListA.Clear ();
                ListA.AddRange (ListB);
            }
        }

        listMaster.Reverse ();

        Debug.Log ("Count=" + listMaster.Count.ToString ());

        foreach (string bundleName in listMaster) {
            string bundleString = bundleName;
            Debug.Log ("bundleName=" + bundleName);

            #if UNITY_IPHONE
            AssetBundle bundleData = AssetBundle.LoadFromFile (Application.dataPath + "/Raw/" + bundleName);
            #elif UNITY_EDITOR
            AssetBundle bundleData = AssetBundle.LoadFromFile (Application.streamingAssetsPath + "/" + bundleName);
            #endif

            if ( bundleData.isStreamedSceneAssetBundle == true ) {
                string[] sceneString = bundleData.GetAllScenePaths ();

                Debug.Log ("scene=" + sceneString [0]);
                string scenePath = Path.GetFileNameWithoutExtension (sceneString [0]);
                SceneManager.LoadSceneAsync (scenePath, LoadSceneMode.Additive);
                return;
            }
            UnityEngine.Object[] objects = bundleData.LoadAllAssets ();

            foreach (UnityEngine.Object obj in objects) {
                Debug.Log ("Name=" + obj.name + " Type=" + obj.GetType ().ToString ());

                if ( obj.GetType () == typeof(GameObject) ) {
                    GameObjectLists.Add (obj as UnityEngine.GameObject);
                    Instantiate (obj);
                } else if ( obj.GetType () == typeof(Texture2D) ) {
                    TextureDic.Add (obj as Texture2D);
                } else if ( obj.GetType () == typeof(Material) ) {
                    Debug.Log ("<color=red>Main Material= " + obj.name + "</color>");
                    MaterialDic.Add (obj as Material);
                }
            }
            //            bundleData.Unload (false);
        }

    }

Android側Unity5.4.0f3 によるシーンアセットバンドルのロード処理(StreamingAssetsフォルダを使用)

Android側Unity5.4.0f3 によるシーンアセットバンドルのロード処理の備忘録

    public List<Texture2D> TextureLists = new List<Texture2D> ();
    public List<Material> MaterialLists = new List<Material> ();
    public List<GameObject> GameObjectLists = new List<GameObject> ();
    List<string> listMaster = new List<string> ();

    public void TestLoc1_Android_BundleLoadStreamingAssets()
    {
        StartCoroutine(loadBundle_StreamingAssets());
    }

    IEnumerator loadBundle_StreamingAssets()
    {
        string loadPath = "jar:file://" + Application.dataPath + "!/assets/AssetBundle/";

        string manifestPath = loadPath + "Android";

        Debug.Log("manifestPath=" + manifestPath);

        var www = WWW.LoadFromCacheOrDownload(manifestPath,1);
        yield return www;
        AssetBundle manifestBundle = www.assetBundle;

        AssetBundleManifest manifest = manifestBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest;

        List<string> ListA = new List<string>();


        ListA.Add(アセットバンドル名1);
        ListA.Add(アセットバンドル名2);
        ListA.Add(アセットバンドル名3);
        ListA.Add(アセットバンドル名4);
        ListA.Add(アセットバンドル名5);
        ListA.Add(アセットバンドル名6);


        ListA.Add(シーンアセットバンドル名);

        listMaster.AddRange(ListA);

        bool noDependenceFlg = false;

        while (noDependenceFlg == false)
        {
            List<string> ListB = new List<string>();
            // 1段階ネストされた依存関係リストを作成
            foreach (string bundlename in ListA)
            {
                // 直接の依存関係リストを取得
                string[] dependenceArray = manifest.GetDirectDependencies(bundlename);

                ListB.AddRange(dependenceArray);
            }

            // 重複排除
            ListB = ListB.Distinct().ToList();

            ListA.Sort();
            ListB.Sort();

            if ((ListB.Count == 0) || (ListA.SequenceEqual(ListB) == true))
            {
                noDependenceFlg = true;
            }
            else {
                // 1段階ネストされた依存関係リストを作成
                foreach (string dependenceBundle in ListB)
                {
                    // すでに存在すれば削除して最後尾に追加
                    if (listMaster.Contains(dependenceBundle) == true)
                    {
                        listMaster.Remove(dependenceBundle);
                    }
                    listMaster.Add(dependenceBundle);
                }
                ListA.Clear();
                ListA.AddRange(ListB);
            }
        }

        listMaster.Reverse();

        Debug.Log("Count=" + listMaster.Count.ToString());


        foreach (string bundleName in listMaster)
        {
            string bundleString = bundleName;
            Debug.Log("bundleName=" + "jar:file://" + Application.dataPath + "!/assets/AssetBundle/" + bundleName);

            var wwwfile = WWW.LoadFromCacheOrDownload("jar:file://" + Application.dataPath + "!/assets/AssetBundle/" + bundleName, 1);
            yield return wwwfile;
            AssetBundle bundleData = wwwfile.assetBundle;

            if ( bundleData.isStreamedSceneAssetBundle == true ) {
                string[] sceneString = bundleData.GetAllScenePaths ();

                string scenePath = Path.GetFileNameWithoutExtension (sceneString [0]);
                SceneManager.LoadSceneAsync (scenePath, LoadSceneMode.Additive);
                return;
            }
            UnityEngine.Object[] objects = bundleData.LoadAllAssets();

            foreach (UnityEngine.Object obj in objects)
            {
                Debug.Log("Name=" + obj.name + " Type=" + obj.GetType().ToString());

                if (obj.GetType() == typeof(GameObject))
                {
                    GameObjectLists.Add(obj as UnityEngine.GameObject);
                    Instantiate(obj);
                }
                else if (obj.GetType() == typeof(Texture2D))
                {
                    TextureDic.Add(obj as Texture2D);
                }
                else if (obj.GetType() == typeof(Material))
                {
                    Debug.Log("<color=red>Main Material= " + obj.name + "</color>");
                    MaterialDic.Add(obj as Material);
                }
            }
            //            bundleData.Unload (false);
        }

    }

【2016/03/04追記】
CreateFromMemoryのバグはバージョン5.2.4で修正された模様

https://unity3d.com/jp/unity/whats-new/unity-5.2.4
■AssetBundles: CreateFromMemory で非圧縮のアセットバンドルをロードしようとするとクラッシュしてしまう問題を修正(698667)

【2015/08/05追記】
CreateFromMemoryと無圧縮アセットバンドル(BuildAssetBundleOptions.UncompressedAssetBundle)の組み合わせ、
CreateFromMemoryImmediateと無圧縮アセットバンドル(BuildAssetBundleOptions.UncompressedAssetBundle)の組み合わせ、には
現在Unity側にバグがあるので使用しないでください(公式見解です)。

無圧縮のアセットバンドルを使用したい時は、CreateFromFile を使用してください。

●Unity5.3.0f4の時

■アセットバンドルのエクスポート

●●無圧縮アセットバンドル●●

BuildPipeline.BuildAssetBundles(出力先, BuildAssetBundleOptions.UncompressedAssetBundle, プラットフォーム);

●●LZMA圧縮アセットバンドル●●

BuildPipeline.BuildAssetBundles(出力先, BuildAssetBundleOptions.None, プラットフォーム);

●●LZ4圧縮アセットバンドル●●

BuildPipeline.BuildAssetBundles(出力先, BuildAssetBundleOptions.ChunkBasedCompression, プラットフォーム);

■アセットバンドルのロード

■WWWを使用してStreamingAssetsからアセットバンドルロード

public List<Object> publicObjectList = new List<Object>();

IEnumerator LoadAssetBundle()
{
    //****************************
    // WWWを使用してStreamingAssetsからアセットバンドルロード
    WWW baseCommonWww = new WWW(Application.streamingAssetsPath + アセットバンドル名);
    yield return baseCommonWww;
    AssetBundle baseCommonBundle = baseCommonWww.assetBundle;
    //****************************
    Object[] baseCommonObjects = baseCommonBundle.LoadAllAssets();

    foreach (Object obj in baseCommonObjects)
    {
        Debug.Log("obj=" + obj.name);
        Debug.Log("objtype=" + obj.GetType().ToString());

        publicObjectList.Add(obj);
    }
}

■LoadFromFileを使用してStreamingAssetsからアセットバンドルロード

public List<Object> publicObjectList = new List<Object>();

メソッド名()
{
	//****************************
	// LoadFromFile LZMA圧縮
	//AssetBundle baseCommonBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + アセットバンドル名);
	// LoadFromFile 圧縮なし
	//AssetBundle baseCommonBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + アセットバンドル名);
	// LoadFromFile LZ4圧縮
	//AssetBundle baseCommonBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + アセットバンドル名);
	//****************************

	Object[] baseCommonObjects = baseCommonBundle.LoadAllAssets();

	foreach (Object obj in baseCommonObjects)
	{
	    Debug.Log("obj=" + obj.name);
	    Debug.Log("objtype=" + obj.GetType().ToString());

	    publicObjectList.Add(obj);
	}
}

■LoadFromFileAsyncを使用してStreamingAssetsからアセットバンドルロード

public List<Object> publicObjectList = new List<Object>();

IEnumerator LoadAssetBundle()
{
    //****************************
    // LoadFromFileAsync LZMA圧縮
    //AssetBundleCreateRequest baseCommonRequest = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + アセットバンドル名);
    // LoadFromFileAsync 圧縮なし
    //AssetBundleCreateRequest baseCommonRequest = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + アセットバンドル名);
    // LoadFromFileAsync LZ4圧縮
    //AssetBundleCreateRequest baseCommonRequest = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + アセットバンドル名);

    //yield return StartCoroutine(BundleRequestWait(baseCommonRequest));
    //AssetBundle baseCommonBundle = baseCommonRequest.assetBundle;
    //****************************

    Object[] baseCommonObjects = baseCommonBundle.LoadAllAssets();

    foreach (Object obj in baseCommonObjects)
    {
        Debug.Log("obj=" + obj.name);
        Debug.Log("objtype=" + obj.GetType().ToString());

        publicObjectList.Add(obj);
    }
}

IEnumerator BundleRequestWait(AssetBundleCreateRequest assetBundleCreateRequest)
{

    while(assetBundleCreateRequest.isDone == false)
    {
        Debug.Log("wait");
        yield return 0;
    }
}

■LoadFromMemoryを使用してStreamingAssetsからアセットバンドルロード

public List<Object> publicObjectList = new List<Object>();

メソッド名()
{
    //****************************
    // LoadFromMemory LZMA圧縮
    //byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み
    // LoadFromMemory 圧縮なし
    //byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み
    // LoadFromMemory LZ4圧縮
    //byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み

    //AssetBundle baseCommonBundle = AssetBundle.LoadFromMemory(bundleData);
    //****************************

	Object[] baseCommonObjects = baseCommonBundle.LoadAllAssets();

	foreach (Object obj in baseCommonObjects)
	{
	    Debug.Log("obj=" + obj.name);
	    Debug.Log("objtype=" + obj.GetType().ToString());

	    publicObjectList.Add(obj);
	}
}

■LoadFromMemoryAsyncを使用してStreamingAssetsからアセットバンドルロード

public List<Object> publicObjectList = new List<Object>();

IEnumerator LoadAssetBundle()
{
    //****************************
    // LoadFromMemoryAsync LZMA圧縮
    //byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み
    // LoadFromMemoryAsync 圧縮なし
    //byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み
    // LoadFromMemoryAsync LZ4圧縮
    byte[] bundleData = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + アセットバンドル名); // 読み込み
    AssetBundleCreateRequest baseCommonRequest = AssetBundle.LoadFromMemoryAsync(bundleData);
    yield return StartCoroutine(BundleRequestWait(baseCommonRequest));
    AssetBundle baseCommonBundle = baseCommonRequest.assetBundle;
    //****************************

    Object[] baseCommonObjects = baseCommonBundle.LoadAllAssets();

    foreach (Object obj in baseCommonObjects)
    {
        Debug.Log("obj=" + obj.name);
        Debug.Log("objtype=" + obj.GetType().ToString());

        publicObjectList.Add(obj);
    }
}

IEnumerator BundleRequestWait(AssetBundleCreateRequest assetBundleCreateRequest)
{

    while(assetBundleCreateRequest.isDone == false)
    {
        Debug.Log("wait");
        yield return 0;
    }
}


●Unity4.6.2の時

■アセットバンドルの作成(圧縮)

ExportAssetBundles.cs
[MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
static void ExportResource()
{

    string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
    {
        // Build the resource file from the active selection.
        Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
               BuildAssetBundleOptions.CollectDependencies  | BuildAssetBundleOptions.CompleteAssets); 
    }
}

■アセットバンドルの作成(非圧縮)

ExportAssetBundles.cs
[MenuItem("Assets/Build AssetBundle From Selection - Track dependencies")]
static void ExportResource()
{

    string path = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "unity3d");
    {
        // Build the resource file from the active selection.
        Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
               BuildAssetBundleOptions.CollectDependencies  
             | BuildAssetBundleOptions.CompleteAssets
             | BuildAssetBundleOptions.UncompressedAssetBundle); 
    }
}

■アセットバンドルのロード(非圧縮)

AssetBundleTestLoader.cs

public void CreateSingleFileLoad()
{
    string path = "C://AssetBundleTest/StreamingAssets/myAssetBundle.unity3d";

    AssetBundle NoCompress = AssetBundle.CreateFromFile(path);

    Object[] selection = NoCompress.LoadAll();

    Instantiate(NoCompress.mainAsset);
        
    NoCompress.Unload(false);
    Debug.Log("Asset End");
        
}

■アセットバンドルのロード(圧縮 LoadAssetBundle_CreateMemory)

LoadAssetBundleData.cs

public void OnLoadAssetBundle()
{
    StartCoroutine(LoadAssetBundle_CreateMemory());
}

IEnumerator LoadAssetBundle_CreateMemory()
{
    // Application.dataPathはAssetsの直下のフォルダの事
    string path = Application.dataPath + "/StreamingAssets/myAssetBundle.unity3d";
    
    WWW www = new WWW("file://" + path);
    yield return www;
    var assetBundleCreateRequest = AssetBundle.CreateFromMemory(www.bytes);
    yield return assetBundleCreateRequest;
    AssetBundle assetBundle = assetBundleCreateRequest.assetBundle;

    Object[] objectArray = assetBundle.LoadAll();
    List<Object> myList = new List<Object>();

    myList.AddRange(objectArray);

    foreach(Object obj in myList)
    {
        Instantiate(obj);
    }
}

■複数アセットバンドルの作成(非圧縮)

ExportAssetBundles.cs

[MenuItem("Assets/Build MultiFolder")]
static void ExportMultiResource()
{
// 保存先のフルパス(Assetsからのパスではない)
string path = "C://AssetBundleTest/StreamingAssets/";
string filename = "myAssetBundle";
string afterpath = ".unity3d";
      
// Prefabsフォルダ内からPrefab拡張子のみのファイルを取得
string[] fs = System.IO.Directory.GetFiles(Application.dataPath + "/Prefabs", "*.prefab");

List<string> BundleList = new List<string>();
List<Object> BundleObjectList = new List<Object>();
BundleList.AddRange(fs);

int index = 0;
foreach(string pathname in BundleList)
{

    // パスから拡張子ありファイル名のみを抽出
    string fileNameLong = System.IO.Path.GetFileName(pathname);
    Debug.Log("fileNameLong=" + fileNameLong);

    // 指定パスよりPrefabを取得
    GameObject BundleObject = Resources.LoadAssetAtPath<GameObject>("Assets/Prefabs/" + fileNameLong);
    // Objectリストに追加
    BundleObjectList.Add(BundleObject);

    // アセットバンドル出力先パス
    string exportfilename = path + filename + index.ToString() + afterpath;
    Debug.Log("BundleName=" + exportfilename);

    // アセットバンドル作成
    BuildPipeline.BuildAssetBundle(BundleObject, BundleObjectList.ToArray(), exportfilename,
                                           BuildAssetBundleOptions.CollectDependencies
                                           | BuildAssetBundleOptions.CompleteAssets
                                           | BuildAssetBundleOptions.UncompressedAssetBundle);

    // 拡張子ありファイル名からファイル名のみを抽出
    string fileName = System.IO.Path.GetFileNameWithoutExtension(fileNameLong);
    Debug.Log("fileName=" + fileName);
    BundleObjectList.Clear();

    index++;
}

■複数アセットバンドルのロード(非圧縮)

AssetBundleTestLoader.cs
public void CreateMultiFileLoad()
{
    // Prefabsフォルダ内からPrefab拡張子のみを取得
    string[] fs = System.IO.Directory.GetFiles("C://AssetBundleTest/StreamingAssets", "*.unity3d");

    List<string> BundleList = new List<string>();
    List<Object> BundleObjectList = new List<Object>();
    BundleList.AddRange(fs);

    foreach (string pathname in BundleList)
    {
        AssetBundle NoCompress = AssetBundle.CreateFromFile(pathname);

        //Object[] selection = NoCompress.LoadAll();

        Instantiate(NoCompress.mainAsset);

        NoCompress.Unload(false);
    }
}

●Unity5.0.0の時

・Prefabをアセットバンドルにしたい時、Inspectorの最下段にあるAssetBundleをクリックして、名前を付ける
 試しにtestcanvasと名付ける
Unity5_AssetBundle_1.png

・アセットバンドル作成用の下記スクリプトを書く
事前にStreamingAssetsフォルダの中にBuildOutPutフォルダを作成する必要あり

ExportAssetBundles.cs

using UnityEngine;
using UnityEditor;
using System.Collections;

public class ExportAssetBundles : MonoBehaviour
{

    [MenuItem("Assets/Unity 5.x Build AssetBundle")]
    static void ExportResource_Unity5()
    {
        Debug.Log("Target=" + EditorUserBuildSettings.activeBuildTarget.ToString());

        // PlatForm名をそのまま出力フォルダとして使用する。
        string OutPutPath = Application.streamingAssetsPath + "/" + EditorUserBuildSettings.activeBuildTarget.ToString();

        // 指定フォルダ存在チェック
        if (Directory.Exists(OutPutPath) == false )
        {
            Directory.CreateDirectory(OutPutPath);
        }

        // プラットフォーム名(Android・iOS)のマニフェストのアセットバンドルが作られる。
        BuildPipeline.BuildAssetBundles(OutPutPath, 0, EditorUserBuildSettings.activeBuildTarget);
        Debug.Log("ComPress End");
    }
}

・メニューより"Unity 5.x Build AssetBundle"をクリック
Unity5_AssetBundle_2.png

・StreamingAssetsの下にBuildOutPutが作成されている。

・BuildOutPutフォルダの中には下記ファイルが作成される。

 BuildOutPut
 BuildOutPut.meta
 BuildOutPut.manifest
 BuildOutPut.manifest.meta
 testcanvas
 testcanvas.meta
 testcanvas.manifest
 testcanvas.manifest.meta

■アセットバンドル ロード(CreateFromFile)

AssetBundleLoad_Unity5.cs
using UnityEngine;
using System.Collections;
public class AssetBundleLoad_Unity5 : MonoBehaviour {
    public void CreateFileAssetBundleFileLoad()
    {
        // マニフェストが入っているファイルをパスで指定
        string path = Application.streamingAssetsPath + "/" + "BuildOutPut" + "/";
        // マニフェストのアセットバンドルを作成
        // (マニフェストのアセットバンドルの中にアセットバンドル化したデータ群が入っている)
        AssetBundle NoCompress = AssetBundle.CreateFromFile(path + "BuildOutPut");
        string[] AssetList = NoCompress.GetAllAssetNames();
        // マニフェスト全アセットバンドルの中身をループ
        foreach (string AssetNames in AssetList)
        {
            // マニフェストのアセットバンドルからマニフェストデータをロード
            AssetBundleManifest manifest = NoCompress.LoadAsset<AssetBundleManifest>(AssetNames);
            // マニフェストから全マニフェスト名を取得
            string[] bundleNames = manifest.GetAllAssetBundles();
            // 全マニフェスト内をループ
            foreach (string bundleName in bundleNames)
            {
                // 指定パスのアセットバンドルを取得
                AssetBundle inBundleName = AssetBundle.CreateFromFile(path + bundleName);
                // 含まれるアセットバンドルリストを取得
                string[] inBundleList = inBundleName.GetAllAssetNames();
                // 指定パスの全アセットバンドル内をループ
                foreach (string inBundleNameString in inBundleList)
                {
                    GameObject prefab = inBundleName.LoadAsset<GameObject>(inBundleNameString);
                    Instantiate(prefab);
                }
            }
        }
    }
}

■アセットバンドル ロード(CreateFromMemory)

AssetBundleManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class AssetBundleManager : MonoBehaviour {

    /// <summary>
    /// UnZip完了後にコールされる
    /// </summary>
    public void CreateFromMemoryLoad()
    {
        StartCoroutine("FromMemoryLoad");
    }

    /// <summary>
    /// UnZipしたByte配列からAssetBundleを取り出す。
    /// </summary>
    /// <returns></returns>
    IEnumerator FromMemoryLoad()
    {
        // Zipファイルリスト内をループ
        foreach (DownLoadData downloaddata in SingletonDownLoadData.Instance.DownLoadDataList)
        {
            List<MemoryStream> UnZipDataList = downloaddata.UnZipDataList;
            List<string> UnZipFileList = downloaddata.FileNameList;

            int test = 0;
            // 解凍したZipファイルリスト内をループ
            foreach(MemoryStream m_stream in UnZipDataList )
            {
                Debug.Log("test=" + test.ToString());
                AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.CreateFromMemory(m_stream.GetBuffer());

                // AssetBundleCreateRequestの完了待ち
                yield return StartCoroutine(WaitBundleRequest(assetBundleCreateRequest));

                AssetBundle assetBundle = assetBundleCreateRequest.assetBundle;
                if (assetBundle != null)
                {
                    string[] AssetList = assetBundle.GetAllAssetNames();
                    // マニフェスト全アセットバンドルの中身をループ
                    foreach (string AssetNames in AssetList)
                    {
                        // マニフェストのアセットバンドルからマニフェストデータをロード
                        AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>(AssetNames);
                        // マニフェストから全バンドル名を取得
                        string[] bundleNames = manifest.GetAllAssetBundles();

                        // 指定マニフェスト内をループ
                        foreach (string bundleName in bundleNames)
                        {
                            int i = 0;
                            AssetBundleCreateRequest TargetAssetBundleCreateRequest = new AssetBundleCreateRequest();
                            foreach (string filename in UnZipFileList)
                            {
                                if (bundleName == filename)
                                {
                                    TargetAssetBundleCreateRequest = AssetBundle.CreateFromMemory(UnZipDataList.ToArray()[i].GetBuffer());
                                    break;
                                }
                                i++;
                            }

                            // ターゲットとなるAssetBundleCreateRequestの完了待ち
                            yield return StartCoroutine(WaitBundleRequest(TargetAssetBundleCreateRequest));
                            // 指定データのアセットバンドルを取得
                            AssetBundle TargetAssetBundle = TargetAssetBundleCreateRequest.assetBundle;

                            // 含まれるアセットバンドルリストを取得
                            string[] inBundleList = TargetAssetBundle.GetAllAssetNames();
                            // 指定データの全アセットバンドル内をループ
                            foreach (string inBundleNameString in inBundleList)
                            {
                                GameObject prefab = TargetAssetBundle.LoadAsset<GameObject>(inBundleNameString);
                                Instantiate(prefab);
                            }
                        }
                    }
                }
                test++;
            }
        }
    }

    /// <summary>
    /// AssetBundleCreateRequestのisDoneを待つ
    /// </summary>
    /// <returns></returns>
    IEnumerator WaitBundleRequest(AssetBundleCreateRequest GetRequest)
    {
        while (GetRequest.isDone == false)
        {
            yield return 0;
        }
    }
}

#■ Unity5.1.0f3 アセットバンドル作成+GZip+Tar

using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using Ionic.Zlib;
using System.IO;
using System.Text;
using System;
using ICSharpCode.SharpZipLib.Tar;
    [MenuItem("Assets/AssetBundle/Export_Android")]
    static void Export_Android_AssetBundle()
    {
        ExportAllAssetBundleIntoAllFile(BuildTarget.Android);
    }

    [MenuItem("Assets/AssetBundle/Export_iOS")]
    static void Export_iPhone_AssetBundle()
    {
        ExportAllAssetBundleIntoAllFile(BuildTarget.iOS);

    }


    static void ExportAllAssetBundleIntoAllFile(BuildTarget Target)
    {
        Debug.Log("Target=" + Target.ToString());

        // 親ディレクトリ+AssetBundleディレクトリ
        string strCurrent = System.IO.Directory.GetCurrentDirectory() + "/" + "AssetBundle";

        // PlatForm名をそのまま出力フォルダとして使用する。
        string OutPutPath = strCurrent + "/" + Target;


        DirectoryInfo di = new DirectoryInfo(OutPutPath);
        // 指定フォルダ存在チェック
        if (Directory.Exists(OutPutPath) == true)
        {
            //フォルダ以下のすべてのファイル、フォルダの属性を削除
            RemoveReadonlyAttribute(di);

            //フォルダを根こそぎ削除
            di.Delete(true);            // 存在すれば削除
        }
        // フォルダを作り直すか新規作成
        Directory.CreateDirectory(OutPutPath);

        // プラットフォーム名(Android・iOS)のマニフェストのアセットバンドルが作られる。
        BuildPipeline.BuildAssetBundles(OutPutPath, BuildAssetBundleOptions.UncompressedAssetBundle, Target);
        Debug.Log("Export End");

        // 拡張子がマニフェストのものを削除
        foreach (string file in Directory.GetFiles(OutPutPath, "*.manifest"))
        {
            File.Delete(file);
        }


        // Gzipフォルダを作成
        Directory.CreateDirectory(OutPutPath + "/Gzip");

        // HTTPリストの作成
        Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");


        // 全ファイルをGzip圧縮
        foreach (string file in Directory.GetFiles(OutPutPath, "*.*"))
        {
            string filename = System.IO.Path.GetFileNameWithoutExtension(file);

            // 出力ファイルの拡張子は「.gz」
            string outFile = OutPutPath + "/Gzip/" + filename  + ".gz";

            int num;
            byte[] buf = new byte[1024]; // 1Kbytesずつ処理する

            FileStream inStream // 入力ストリーム
              = new FileStream(file, FileMode.Open, FileAccess.Read);

            // ファイルサイズをバイトに変換
            byte[] filesizehedder = new byte[8];
            filesizehedder = BitConverter.GetBytes(inStream.Length);


            FileStream outStream // 出力ストリーム
              = new FileStream(outFile, FileMode.Create);

            GZipStream compStream // 圧縮ストリーム
              = new GZipStream(
                outStream,  // 出力先となるストリームを指定
                CompressionMode.Compress); // 圧縮を指定

            using (inStream)
            using (outStream)
            using (compStream)
            {
                //compStream.Write(filesizehedder, 0, 8);

                while ((num = inStream.Read(buf, 0, buf.Length)) > 0)
                {
                    compStream.Write(buf, 0, num);
                }
            }
        }



        // Tarフォルダを作成
        Directory.CreateDirectory(OutPutPath + "/Gzip/Tar");

        StreamWriter writer =
          new StreamWriter(OutPutPath + "/Gzip/Tar/httplist.txt", true, sjisEnc);
        // 全ファイルGzipをTarアーカイブにする
        foreach (string file in Directory.GetFiles(OutPutPath + "/Gzip", "*.*"))
        {
            string filename = System.IO.Path.GetFileNameWithoutExtension(file);
            // 出力ファイルの拡張子は「.tar」
            string outFile = OutPutPath + "/Gzip/Tar/" + filename + ".tar";

            Debug.Log("filename=" + filename);
            Debug.Log("outFile=" + outFile);
            // Tarファイル作成
            CreateTar(outFile, file);
            // HTTPリストに書き込み
            writer.WriteLine("DownLoadUrlAdd(" + "\"" + "http://999.99.99.999/Tar/" + Path.GetFileName(outFile) + "\"" + ");");
            Debug.Log("WriteLine");

        }
        writer.Close();

        Debug.Log("HttpList End");

    }

    /// <summary>
    /// Tarファイル作成
    /// </summary>
    /// <param name="outputTarFilename">Output .tar.gz file</param>
    /// <param name="sourceDirectory">Input directory containing files to be added to GZipped tar archive</param>
    private static void CreateTar(string outputTarFilename, string readfilename)
    {
        using (FileStream fs = new FileStream(outputTarFilename, FileMode.Create, FileAccess.Write, FileShare.None))
        using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(fs))
        {
            TarEntry tarEntry = TarEntry.CreateEntryFromFile(readfilename);
            tarArchive.WriteEntry(tarEntry, true);
        }
    }
76
65
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
76
65