using Cysharp.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class AssetBundleInfo
{
public string path;
public string description;
}
namespace JGTools
{
public class AssetBundleHelper
{
#region 加载assetbundle
public static IEnumerator LoadAB(AssetBundleInfo assetBundleInfo)
{
AssetBundle assetBundle = null;
using (FileStream stream = new FileStream(assetBundleInfo.path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.LoadFromStreamAsync(stream);
yield return assetBundleCreateRequest;
assetBundle = assetBundleCreateRequest.assetBundle;
}
if (assetBundle == null)
{
Response(false, null, assetBundleInfo);
yield break;
}
string[] names = assetBundle.GetAllAssetNames();
if (names.Length > 0)
{
var assetLoadRequest = assetBundle.LoadAssetAsync<GameObject>(names[0]);
yield return assetLoadRequest;
GameObject prefab = assetLoadRequest.asset as GameObject;
if (prefab != null)
{
Response(true, prefab, assetBundleInfo);
}
}
else
{
Response(false, null, assetBundleInfo);
}
assetBundle.Unload(false);
}
public static void Response(bool success, GameObject prefab, AssetBundleInfo abinfo)
{
}
#endregion
public static async UniTask LoadAssetBundleAsync(string path)
{
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(path);
var operation = request.SendWebRequest();
await operation.ToUniTask();
if (request.result == UnityWebRequest.Result.Success)
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
// 在这里进行您需要的操作,例如加载资源等
string[] names = bundle.GetAllAssetNames();
if (names.Length > 0)
{
if (names.Length > 0)
{
var assetLoadRequest = bundle.LoadAssetAsync<GameObject>(names[0]);
GameObject prefab = assetLoadRequest.asset as GameObject;
if (prefab != null)
{
Debug.Log(prefab.name);
//Response(true, prefab, path);
GameObject.Instantiate(prefab);
}
}
else
{
//Response(false, null, path);
}
}
bundle.Unload(false);
}
else
{
Debug.LogError("Failed to load Asset Bundle: " + request.error);
}
}
}
}
【Unity】AssetBundle(UniTask)加载
最新推荐文章于 2024-03-20 21:00:00 发布