AssetBundle 具体使用代码

//AssetBundle

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;//引入命名空间
using System.IO;//引入文件读取相关的命名空间

public class BundleTool : EditorWindow
{
string sourcePath;//需要打包的原始资源的路径
string outPath;//资源打包成Assetbundle包之后存放的路径
[MenuItem(“Tools/BundleTool”)]
static void OpenWindow()
{
BundleTool btWindow = EditorWindow.GetWindow< BundleTool>();//打开一个窗口
btWindow.Show();
btWindow.Init();
}
void Init()
{
sourcePath = Application.dataPath + “/AssetBundle”;
outPath = Application.streamingAssetsPath;
}
void SetBundleName(string path)
{
string[] files = Directory.GetFiles(path);
for(int i = 0; i < files.Length; i++)
{
if (files[i].EndsWith(".meta"))
{
continue;
}
//Debug.Log(files[i]);
/C:/ Users / Students_029 / Desktop / woerjianmin / AngryBots2_Cinemachine / AssetBundle / Assets / AssetBundle\New Material.mat/
string filepath = files[i].Replace("\","/");
//Debug.Log(filepath);
//C:/Users/Students_029/Desktop/woerjianmin/AngryBots2_Cinemachine/AssetBundle/Assets/AssetBundle/New Material.mat
filepath = filepath.Replace(Application.dataPath + “/”,"");
//Debug.Log("最后路径: " + filepath);
//最后路径: AssetBundle/New Material.mat
//打包名字赋值
AssetImporter impoter = AssetImporter.GetAtPath(“assets/” + filepath);
impoter.assetBundleName = filepath;
}
//递归调用:每个文件夹下的多个文件,进行打包名字的设置
string[] directories = Directory.GetDirectories(path);//获取到所有的文件夹
for (int i = 0; i < directories.Length; i++)
{
SetBundleName(directories[i]);//单个文件设置名字
//Debug.Log(“所有文件夹的路径” + directories[i]);
}
}
void BuildBundle()
{
//打包的三个参数: 打包之后的输出存放路径,参数二: 打包的选择,参数三:打包的平台(EditorUserBuildSettings.activeBuildTarget)自动选择当前激活的平台
BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);
}
void setnameandbuildbundle()
{
SetBundleName(sourcePath);
BuildBundle();
}
private void OnGUI()
{
//if (GUILayout.Button(“SetBundleName”))
//{
// SetBundleName(sourcePath);
//}
//if (GUILayout.Button(“BuildBundle”))
//{
// BuildBundle();
//}
if (GUILayout.Button(“setnameandbuildbundle”))
{
setnameandbuildbundle();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class AssetBundleManager
{
//集合:存放已经下载过的AssetBundle在内存中的缓存
public Dictionary<string, AssetBundle> allAassetBundles = new Dictionary<string, AssetBundle>();

//AssetBundle的资源服务器的地址
//public string serverLoadPath = Application.streamingAssetsPath;
public string serverLoadPath = "服务器地址";
private static AssetBundleManager _instance;
public static AssetBundleManager Instacne
{
    get
    {
        if(_instance == null)
        {
            _instance = new AssetBundleManager();
        }
        return _instance;
    }
}
private AssetBundleManifest _mainfest;//总的AssetBundle包资源
public AssetBundleManifest Mainfest
{
    get
    {
        if(_mainfest == null)
        {
            //AssetBundle assetBundle = AssetBundle.LoadFromFile(serverLoadPath + "StreamingAssets");
            AssetBundleManifest是总的Bundle资源包的数据,位于StreamingAssets这个文件里面。路径是serverLoadPath + "/StreamingAssets"
            //_mainfest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
            //从服务器上加载
            UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(serverLoadPath + "/StreamingAssets");
            request.SendWebRequest();
            while (!request.isDone){ }
            AssetBundle assetBundle = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
            _mainfest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        }
        return _mainfest;
    }
}
//加载相互依赖的关系Bundle包
public void LoadBundle(string bundleName,string filename)
{
    //denpencies  是需要加载的bundle的依赖关系的资源的包的名字
    string[] Dependencies = Mainfest.GetAllDependencies(bundleName);
    //遍历输出跟要加载的bundleName包,有依赖系的所有的Bundle包
    //foreach (var item in Dependencies)
    //{
    //    Debug.Log(item);
    //}
    //调用方法
    DownLoadAssets.Instance.StartDownLoad(bundleName, Dependencies, filename);
}
//外界调用的入口,加载贴图
public void LoadAndSetTexture(string bundleName, string filename,Renderer render)
{
    DownLoadAssets.Instance.StartLoadAndSetTexture(bundleName, filename, render);
}

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AssetBundleTest : MonoBehaviour
{
public GameObject plane;
void Start()
{

}

void Update()
{
    if (Input.GetKeyDown(KeyCode.O))
    {
        AssetBundleManager.Instacne.LoadBundle("assetbundle/prefabs/cylinder.prefab", "cylinder");
    }
    if (Input.GetKeyDown(KeyCode.P))
    {
        AssetBundleManager.Instacne.LoadAndSetTexture("assetbundle/textures/bark2_topbottom_atmn.tga", "bark2_topbottom_atmn", plane.GetComponent<Renderer>());
    }
    if (Input.GetKeyDown(KeyCode.L))
    {
        //一般在释放内存和资源时用
        //Unload函数:(传入true):卸载掉已经加载过的当前的Bundle包但Load出来的资源对象材质不会消失,不会对已经加载出来的对象产生影响
        AssetBundleManager.Instacne.allAassetBundles["assetbundle/textures/bark2_topbottom_atmn.tga"].Unload(false);
        /*
        //Unload函数:(传入true):卸载掉已经加载过的当前的Bundle包和Load出来的资源对象
        //具有相互依赖关系的资源对象进行卸载的过程中,卸载其中一个Bundle包时,引用关系被破坏
        //卸载贴图
        AssetBundleManager.Instacne.allAassetBundles["assetbundle/textures/bark2_topbottom_atmn.tga"].Unload(true);
        AssetBundleManager.Instacne.allAassetBundles.Remove("assetbundle/textures/bark2_topbottom_atmn.tga");
        //卸载材质
        AssetBundleManager.Instacne.allAassetBundles["assetbundle/material/tag.mat"].Unload(true);
        AssetBundleManager.Instacne.allAassetBundles.Remove("assetbundle/material/tag.mat");
        //卸载预制体
        AssetBundleManager.Instacne.allAassetBundles["assetbundle/prefabs/cylinder.prefab"].Unload(true);
        AssetBundleManager.Instacne.allAassetBundles.Remove("assetbundle/prefabs/cylinder.prefab");*/

    }
}

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;//引入命名空间

public class DownLoadAssets : MonoBehaviour
{
//单例模式
public static DownLoadAssets Instance;
// Start is called before the first frame update
void Start()
{
Instance = this;
}
public void StartDownLoad(string assetBundleName, string[] deps, string filename)
{
StartCoroutine(DownLoad(assetBundleName,deps,filename));
}

IEnumerator DownLoad(string assetBundleName, string[] deps, string filename)
{
    //先加载依赖关系的Bundle包
    for (int i = 0; i < deps.Length; i++)
    {
        if (AssetBundleManager.Instacne.allAassetBundles.ContainsKey(deps[i]))
        {
            continue;
        }
        //参数一:资源url路径链接 
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleManager.Instacne.serverLoadPath + "/" + deps[i]);
        yield return request.SendWebRequest();//发送请求并等待加载
        //将加载过的Bundle包放入到字典集合中
        AssetBundleManager.Instacne.allAassetBundles.Add(deps[i],(request.downloadHandler as DownloadHandlerAssetBundle).assetBundle);
    }
    //依赖关系Bundle包加载完成后,再去加载需要的当前资源对象的bundle包
    AssetBundle assetBundle;
    if (AssetBundleManager.Instacne.allAassetBundles.ContainsKey(assetBundleName))
    {
        assetBundle = AssetBundleManager.Instacne.allAassetBundles[assetBundleName];
    }
    else
    {
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleManager.Instacne.serverLoadPath + "/" + assetBundleName);
        yield return request.SendWebRequest();//等待加载
        assetBundle = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
        AssetBundleManager.Instacne.allAassetBundles.Add(assetBundleName, assetBundle);
    }
    GameObject obj = assetBundle.LoadAsset<GameObject>(filename);
    Instantiate(obj);
}
public void StartLoadAndSetTexture(string bundleName,string filename,Renderer render)
{
    StartCoroutine(LoadAndSetTeture(bundleName,filename,render));//调用协同程序
}
IEnumerator LoadAndSetTeture(string assetBundleName,string filename,Renderer render)
{
    AssetBundle assetBundle;
    if (AssetBundleManager.Instacne.allAassetBundles.ContainsKey(assetBundleName))//如果贴图的Bundle包已经存在
    {
        assetBundle = AssetBundleManager.Instacne.allAassetBundles[assetBundleName];
    }
    else
    {
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleManager.Instacne.serverLoadPath + "/" + assetBundleName);
        yield return request.SendWebRequest();//等待加载
        assetBundle = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
        AssetBundleManager.Instacne.allAassetBundles.Add(assetBundleName, assetBundle);
    }
    Texture teture = assetBundle.LoadAsset<Texture>(filename);//从AssetBundle包里面加载Texture类型
    render.material.mainTexture = teture;//将material里面的贴图换成该贴图 贴图绑定
    
}
// Update is called once per frame
void Update()
{
    
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值