LoginSignup
34
33

More than 5 years have passed since last update.

【Unity】AssetBundleとりあえず使ってみた

Last updated at Posted at 2014-11-06

1.AssetBundleとは?

Assetが多くなってしまうとiOS、Androidアプリのサイズ問題が浮上してくる。
その問題を解決する一つの手段がAssetBundle。
本当にざっくりとした説明をすると「Unity上で生成したアーカイブファイルをサーバーに置いてダウンロードしUnity上で使用する」そんな感じのもの。

AssetBundleに含められるファイルは
・GameObject
・Material
・Texture
・Prefab....etc

※参考サイト(ひささん日記)
http://tech.hisasann.com/cs/183/

上記ファイルをまとめてアーカイブし必要なタイミングで取得する。

2.AssetBundleを作る準備

AssetBundleを作るには、Unity Editorに対してAsset Bundleを生成するパイプライン機能を追加する必要がある。

まずはUnityを起動し、AssetにEditorフォルダを追加。
次にEditorフォルダ内にScriptを追加。

ファイル名:ExportAssetBundles.cs
ExportAssetBundles.cs
using UnityEngine;
using UnityEditor;

public class ExportAssetBundles {

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

        // 保存ウィンドウのパネルを表示
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");
        if (path.Length != 0) {

            // アクティブなセレクションに対してリソースファイルをビルド
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

            BuildPipeline.BuildAssetBundle( Selection.activeObject, selection, path, 
                BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets);
                Selection.objects = selection;
        }
    }
    [MenuItem("Assets/Build AssetBundle From Selection - No dependency tracking")]
    static void ExportResourceNoTrack () {
        // 保存ウィンドウのパネルを表示
        string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");

        if (path.Length != 0) {
            // アクティブなセレクションに対してリソースファイルをビルド
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, path);
        }
    }
}

※上記ソース自体はここから
http://docs-jp.unity3d.com/Documentation/ScriptReference/BuildPipeline.BuildAssetBundle.html

3.適当なPrefabをAssetBundleとしてBuildしてみる

2で作成したScriptにミスがなければ右クリックメニューに「Build AssetBundle〜」が追加されるので、適当なPrefabを作成しアーカイブしてみよう。

①Cubeを追加
②CubeをPrefab化
③Prefab化したCubeを右クリック
④「Build AssetBundle From Selection – Track dependencies」を実行

ファイルの保存ダイアログが出たら、適当なフォルダに保存。名前は自分の好きな名前で。

4.生成したAssetBundleをサーバーに配置

Dropboxのpublicでも良いし、自分のサーバーでも良い。
配置が完了したらそのurlを把握しておこう。

5.実際にAssetBundleを使ってみる

新規にScriptを追加し実際にAssetBundleを使用してみる。

ファイル名:CachingLoadExample.cs
CachingLoadExample.cs
using System;
using UnityEngine;
using System.Collections;

public class CachingLoadExample : MonoBehaviour
{
    void Start ()
    {
        // Clear Cache
        Caching.CleanCache();

        string url = "〜〜ここにURLを入力〜〜";

        StartCoroutine (DownloadAndCache ("Cube",url,1));
    }

    public IEnumerator DownloadAndCache (string assetName, string url, int version = 1)
    {
        // キャッシュシステムの準備が完了するのを待ちます
        while (!Caching.ready)
            yield return null;

        // 同じバージョンが存在する場合はアセットバンドルをキャッシュからロードするか、
        //  またはダウンロードしてキャッシュに格納します。
        using (WWW www = WWW.LoadFromCacheOrDownload (url, version)) {
            yield return www;
            if (www.error != null) {
                throw new Exception ("WWWダウンロードにエラーがありました:" + www.error);
            }

            AssetBundle bundle = www.assetBundle;
            if (assetName == "")
                Instantiate (bundle.mainAsset);
            else
                Instantiate (bundle.Load (assetName));
            // メモリ節約のため圧縮されたアセットバンドルのコンテンツをアンロード
            bundle.Unload (false);

        } // memory is freed from the web stream (www.Dispose() gets called implicitly)
    }
}

※参考ソース
http://docs-jp.unity3d.com/Documentation/Manual/DownloadingAssetBundles.html

入力が完了したら空のGameObjectを作成しシーンに追加 -> Scriptをアタッチ。
起動を行なうと画面にCubeが出現するはず。

追記

実行時にエラーが発生した場合、Editor上でドメインの指定がされていない事が原因かと思うので、
Edit -> ProjectSetting -> Editorを選択し表示されたInspectorの「WWW Security Emulation」に
AssetBundleを配置したサーバーのドメインを記述しておこう。

34
33
0

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
34
33