U3D-Assetbundle加载

本文介绍了一个Unity中用于创建和加载Assetbundle的脚本示例。通过放置脚本在Editor文件夹下,可以实现资源的批量打包。此外,还提供了两种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);
    }
}

 

转载于:https://www.cnblogs.com/mukeyang/p/4522679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值