首先是创建AssetBundle(一下简称AB包),在Assets中点击资源,修改器AssetBundle不为NONE
创建脚本,输入如下代码
using System.IO;
using UnityEditor;
using UnityEngine;
public class CreateAssetBundles : MonoBehaviour
{
[MenuItem(“AssetBundle/Package1”)]
private static void PackageBuddle()
{
Debug.Log(“Packaging AssetBundle…”);
string packagePath = UnityEditor.EditorUtility.OpenFolderPanel(“Select Package Path”, “G:/FarmsWebGL”, “”);
if (packagePath.Length <= 0 || !Directory.Exists(packagePath))
return;
Debug.Log("Output Path: " + packagePath);
BuildPipeline.BuildAssetBundles(packagePath, BuildAssetBundleOptions.None, BuildTarget.WebGL);
AssetDatabase.Refresh();
}
}
这个时候会生成一个新的菜单,点击AssetBundle/Package1会生成AB包,会将所有设置了AssetBundle的物体全部打包。
打包完成之后便要进行加载,
使用如下代码
IEnumerator Download()
{
//ab包的地址
AssetBundle ab;
using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri,1))
{
//yield return request.SendWebRequest();
request.SendWebRequest();
while (!request.isDone)
{
Debug.Log(request.downloadProgress);
//textProgress.text = (request.downloadProgress * 100).ToString(“F0”) + “%”;
yield return null;
}
if (request.isDone)
{
Debug.Log(100);
//textProgress.text = 100 + “%”;
}
ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
if (ab == null)
{
Debug.LogError(“AB包为空”);
yield break;
}
}
Instantiate(ab.LoadAsset(“Cube.prefab”));
yield break;
}
设置好路径,便可加载到场景中