-
第一部分
打包
using UnityEditor;
using System.IO;
public class CreateAssetBundles
{
string assetBundleDirectory = "Assets/AssetBundles" ;
if(!Directory.Exists(assetBundleDirectory ))
{
Directory.CreateDirectory(assetBundleDirectory);
}
/*--打包-
* 参数一:打包到哪个文件夹
* 参数二:打包方式
* 参数三:打包平台
*/
BuildPipeline.BuildAssetBundles(assetBundleDirectory,
BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows);
}
- 第二部分
加载方式
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class LoadAssetBundles : MonoBehaviour
{
private void Start()
{
//StartCoroutine(LoadAB_ByMemoryAsync("Assets/AssetBundles/prefab.player", "firewizard"));
//LoadAB_ByMemory("Assets/AssetBundles/prefab.player", "firewizard");
//LoadAB_ByFile("Assets/AssetBundles/prefab.player", "firewizard");
//StartCoroutine(LoadAB_ByFileAsync("Assets/AssetBundles/prefab.player", "firewizard"));
//StartCoroutine(LoadAB_ByWeb("AssetBundles/prefab.player", "firewizard"));
}
/// <summary>
/// 二进制文件 同步加载
/// </summary>
/// <param name="path"></param>
/// <param name="objName"></param>
private void LoadAB_ByMemory(string path, string objName)
{
AssetBundle ab = AssetBundle.LoadFromMemory(File.ReadAllBytes(path));
GameObject go = ab.LoadAsset<GameObject>(objName);
Instantiate(go);
}
/// <summary>
/// 二进制文件 异步加载
/// </summary>
/// <param name="path"></param>
/// <param name="objName"></param>
/// <returns></returns>
IEnumerator LoadAB_ByMemoryAsync(string path, string objName)
{
AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
yield return request;
AssetBundle ab = request.assetBundle;
GameObject go = ab.LoadAsset<GameObject>(objName);
Instantiate(go);
}
/// <summary>
/// 普通文件 同步加载
/// </summary>
/// <param name="path">资源路径</param>
/// <param name="objName">资源名称</param>
private void LoadAB_ByFile(string path, string objName)
{
AssetBundle ab = AssetBundle.LoadFromFile(path);
GameObject go = ab.LoadAsset<GameObject>(objName);
Instantiate(go);
}
/// <summary>
/// 普通文件 异步加载
/// </summary>
/// <param name="path"></param>
/// <param name="objName"></param>
/// <returns></returns>
IEnumerator LoadAB_ByFileAsync(string path, string objName)
{
AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
yield return request;
AssetBundle ab = request.assetBundle;
GameObject go = ab.LoadAsset<GameObject>(objName);
Instantiate(go);
}
/// <summary>
/// 网页请求进行加载
/// </summary>
/// <param name="path"></param>
/// <param name="objName"></param>
/// <returns></returns>
IEnumerator LoadAB_ByWeb(string path, string objName)
{
string url = "file:///" + Application.dataPath + "/" + path;
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url, 0);
yield return request.SendWebRequest();
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
GameObject go = ab.LoadAsset<GameObject>(objName);
Instantiate(go);
}
}
还有更多的加载方式,后续更新。小白自己整理,有误望谅解。
谢谢