1、参考资料
https://gameinstitute.qq.com/community/detail/100031
https://www.cnblogs.com/Roz-001/p/11237198.html
2、生成AB包
首先给资产文件指定包名,然后代码生成对应的ab包。
同一AB包内的资产名称不能重复
using System.IO;
using UnityEditor;
using UnityEngine;
public class AssetBundlesBuilder
{
const string _assetBundleDirectory = "Assets/AssetBundles";
[MenuItem("Assets/Build AssetBundles")]
static void BuildAllAssetBundles()
{
if (!Directory.Exists(_assetBundleDirectory))
{
Directory.CreateDirectory(_assetBundleDirectory);
}
BuildPipeline.BuildAssetBundles(_assetBundleDirectory, BuildAssetBundleOptions.None,
BuildTarget.StandaloneWindows);
}
}
3、加载AB包中的资产
更多加载方式见参考连接。可以自行构建包和文件路径的对应关系表实现根据项目中的文件路径加载AB包中的资源。
using System.IO;
using UnityEditor;
using UnityEngine;
public class ABLoader
{
AssetBundle _ab;
public ABLoader(string abPath)
{
_ab = AssetBundle.LoadFromFile(abPath);
}
public GameObject Load(string name)
{
GameObject go = _ab.LoadAsset<GameObject>(name);
return go;
}
}
using System;
using UnityEngine;
public class Test : MonoBehaviour
{
void OnEnable()
{
var abLoader = new ABLoader("Assets/AssetBundles/objs");
var go = abLoader.Load("AB_Cube");
GameObject.Instantiate(go);
}
}