Unity AssetBundle的使用两种方法
1、所有打包参数在代码里设置,完全代码控制;第一种:
在代码中指定bundle包名,指定包含在该bundle里的所有资源路径
新建TestBundle.cs注意此脚本放在Editor文件夹下,
using UnityEngine;
using UnityEditor;
using System.IO;
public static class TestBundle
{
static void BuildAB()
{
string path = Application.streamingAssetsPath + "/AssetsBundles/";
if (Directory.Exists(path))
Directory.Delete(path, true);
Directory.CreateDirectory(path);
AssetBundleBuild[] buildMap = new AssetBundleBuild;
//指定bundle包名
buildMap.assetBundleName = "prefab_bundle";
string[] assets = new string;
assets = "Assets/AssetsBundleObj/Cube.prefab"; // 必须是完整的文件名(包括后缀)
assets = "Assets/AssetsBundleObj/Sphere.prefab";
//指定bundle包含的资源路径数组
buildMap.assetNames = assets;
buildMap.assetBundleName = "scene_bundle";
string[] scenes = new string;
scenes = "Assets/_Scenes/Scene.unity";
buildMap.assetNames = scenes;
BuildPipeline.BuildAssetBundles(path, buildMap, BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneWindows);
}
}
代码中设置参数
2、在编辑器中设置打包参数,代码简便
新建一个prefab,如下配置,一个名字,一个后缀
新建TestBundle.cs注意此脚本放在Editor文件夹下,代码如下:
using UnityEngine;
using UnityEditor;
using System.IO;
public static class TestBundle
{
static void BuildAB2()
{
string path = Application.streamingAssetsPath + "/AssetsBundles/";
if (Directory.Exists(path))
Directory.Delete(path, true);
Directory.CreateDirectory(path);
BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneOSX);
}
} 再新建一个脚本AssetBundleTest.cs 代码如下, using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AssetBundleTest : MonoBehaviour
{
public GameObject obj;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
if (GUILayout.Button("加载预制体Cube"))
{
StartCoroutine(LoadObj("cube_ab", "cube.prefab"));//有没有.prefab后缀都正常加载
}
if (GUILayout.Button("加载预制体Sphere"))
{
StartCoroutine(LoadObj("prefab_bundle", "sphere"));
}
}
/// <summary>
/// 加载预制体
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
IEnumerator LoadObj(string bundle_name, string name)
{
string path = "file://" + Application.streamingAssetsPath + "/AssetsBundles/" + bundle_name;
//Debug.LogError(string.Format("obj{0}", path));
WWW www = new WWW(path);
yield return www;
if (www.error == null)
{
AssetBundle bundle = www.assetBundle;
//这里LoadAsset第二个参数 有没有都能正常运行,这个类型到底什么用途还有待研究
obj = Instantiate(bundle.LoadAsset(name, typeof(GameObject))) as GameObject;
obj.transform.parent = transform;
// 上一次加载完之后,下一次加载之前,必须卸载AssetBundle,不然再次加载报错:
// The AssetBundle 'Memory' can't be loaded because another AssetBundle with the same files is already loaded
bundle.Unload(false);
}else
{
Debug.LogError(www.error);
}
}
}
工具栏中会出现
点击生成bundle目录,会看到AssetBundle文件夹在StreamingAssets目录中,
将AssetBundleTest.js绑定到场景中运行,点击“加载预制体Cube”cube就会出现在场景中了。
页:
[1]