1.命名
命名注意:sky表示生成的目录 sky01 是ab包的名字。 ab是生成文件的后缀名
2.打包脚本
[MenuItem("ThrusdayFrame/Build AssetBundle")]
public static void BuildBundle()
{
string dir = "AssetBundles";
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
//BuildTarget 选择build出来的AB包要使用的平台
BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
}
3.加载脚本,以网络地址下载天空和材质球更换为例。
IEnumerator DoChangeOnLine(string key)
{
//网络地址
string str = "http://192.168.1.121/AssetBundles/sky/sky" + key + ".ab";
//下载
UnityWebRequest wb = UnityWebRequestAssetBundle.GetAssetBundle(str);
yield return wb.SendWebRequest();
//获取
AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(wb);
if (wb.isDone)
{
Debug.Log(wb.error);
temp = RenderSettings.skybox.GetFloat("_Exposure");
while (temp > 0.01f)
{
temp -= Time.deltaTime * changeSpeed;
temp = Mathf.Clamp(temp, 0, 1);
RenderSettings.skybox.SetFloat("_Exposure", temp);
yield return null;
}
//替换
RenderSettings.skybox = assetBundle.LoadAssetAsync<Material>("Mat_" + key).asset as Material;
blackToDo?.Invoke();
RenderSettings.skybox.SetFloat("_Exposure", 0);
temp = RenderSettings.skybox.GetFloat("_Exposure");
while (temp < 0.99f)
{
temp += Time.deltaTime * changeSpeed;
temp = Mathf.Clamp(temp, 0, 1);
RenderSettings.skybox.SetFloat("_Exposure", temp);
yield return null;
}
}
yield return null;
}
1.当浏览器报错:Asset Bundle is download compelet , but no data has been received !
这时:服务器配置中 HTTP响应标头 中需要添加一项:
key | Access-Control-Allow-Origin |
value | * |
2.web服务器根目录需要放置web.config 点此下载。或者自己配置MIME类型,注意,AB包后缀名需要一起配置进去,加入AB后缀名为 .ab 则需要在MIME中添加一项:
key | .ab |
value | application/octet-stream |