Unity加载AB包
1、导入AB资源包
2、打开操作面板
3、代码加载场景
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public class LoadAB : MonoBehaviour
{
AssetBundle ab;
private string abPath = "路径";
public Slider ab_slider;
public TextMeshProUGUI ab_text;
IEnumerator Start()
{
string path = Application.streamingAssetsPath + "/" + abPath;
using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path))
{
request.SendWebRequest();
while (ab_slider.value <= 0.99)
{
ab_slider.value = Mathf.Lerp(ab_slider.value, request.downloadProgress, Time.deltaTime);
ab_text.text = (int)(ab_slider.value * 100) + "%";
yield return null;
}
if (request.isDone)
{
ab_text.text = 100 + "%";
}
ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
if (ab == null)
{
Debug.LogError("AB包为空");
yield break;
}
}
ab_slider.gameObject.SetActive(false);
SceneManager.LoadScene("场景名");
}
}
4、代码加载预制体
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public class LoadAB_Prefabs : MonoBehaviour
{
AssetBundle ab;
private string abPath = "路径";
IEnumerator Start()
{
string path = Application.streamingAssetsPath + "/" + abPath;
using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path))
{
request.SendWebRequest();
while (request.downloadProgress <= 0.99)
{
yield return null;
}
if (request.isDone)
{
ab = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
if (ab == null)
{
Debug.LogError("AB包为空");
yield break;
}
}
}
GameObject ab_obj = Instantiate(ab.LoadAsset<GameObject>("预制体名"));
}
}