U3D-Assetbundle加载

首先 写个打包成Assetbundle的脚本 放在Editor下

using UnityEngine;
using System.Collections;
using UnityEditor;

public class NewBehaviourScript :ScriptableObject
{
    [MenuItem("chen/create assetbundle main")]
    static void cam()
    { 
        object[] selected = Selection.GetFiltered(typeof(object), SelectionMode.DeepAssets);
        foreach (Object obj in selected)
        { 
            string source = AssetDatabase.GetAssetPath(obj);
            string target = Application.dataPath + "/chensiyang/" + obj.name + ".assetbundle";
            if (BuildPipeline.BuildAssetBundle(obj, null, target, BuildAssetBundleOptions.CollectDependencies))
                Debug.Log("yes");
            else
                Debug.Log("wrong");
        }
    }
    [MenuItem("chen/create assetbundle all")]
    static void caa()
    { 
        Object[] selectedall = Selection.GetFiltered(typeof(object),SelectionMode.DeepAssets);
        string aim = Application.dataPath + "/chensiyang/all.assetbundle";
        if (BuildPipeline.BuildAssetBundle(null, selectedall, aim, BuildAssetBundleOptions.CollectDependencies))
            Debug.Log("all");
        else Debug.Log("wrong");
    }

}

 

然后加载包

using UnityEngine;
using System.Collections;
using System.IO;

public class NewBehaviourScript2 : MonoBehaviour {
    private  static string path ="file://"+Application.dataPath+"/chensiyang/";
    // Use this for initialization
    void Start () {
        print(Application.dataPath);

        StartCoroutine(load(path + "all.assetbundle"));
    }
    
    // Update is called once per frame
    void Update () {
    //if(Input.GetMouseButtonDown(0))
        
    }
    private IEnumerator load(string str)
    { 
        WWW data = new WWW(str);
        yield return data;
         Instantiate(data.assetBundle.Load("tv"));
        data.assetBundle.Unload(false);

    }
}

 还有一种加载方式,避免重复下载

 private IEnumerator load(string str)
    {
        //WWW data = new WWW(str);
        //yield return data;
        //Instantiate(data.assetBundle.Load("tv"));
        //data.assetBundle.Unload(false);
        WWW data = WWW.LoadFromCacheOrDownload(str, 5);
        yield return data;
       yield return Instantiate(data.assetBundle.Load("tv"));
        data.assetBundle.Unload(false);
    }
}

 

posted @ 2015-05-22 16:29  mukeyang  阅读(222)  评论(0编辑  收藏  举报