第二步:加载AB包的资源,用于显示
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.U2D;
using UnityEngine.UI;
public class GameLaunch : MonoBehaviour
{
public Button Btn;
public Button Btn2;
private string bundlePath = "";
private string bundlePath2 = "";
public Transform Parent_;
public Image IMG;
void Start()
{
bundlePath =Path.Combine(Application.streamingAssetsPath + "/AB/","prefab_ui") ;
bundlePath2 =Path.Combine(Application.streamingAssetsPath + "/AB/","prefab_altlas") ;
Btn.onClick.AddListener(() =>
{
//加载资源
// 同时启动两个异步加载过程
StartCoroutine(LoadAssetBundlesAsync());
});
Btn2.onClick.AddListener(() =>
{
StartCoroutine(LoadAssetBundlesAsync2());
});
}
IEnumerator LoadAssetBundlesAsync()
{
// 同时启动两个异步加载过程
yield return StartCoroutine(LoadAssetBundleAsync(bundlePath2, "_图集_AB", "Atlas_One","ui_frame_fight"));
}
IEnumerator LoadAssetBundlesAsync2()
{
// 同时启动两个异步加载过程
yield return StartCoroutine(LoadAssetBundleAsync(bundlePath, "_UI_AB", "Prefab_One"));
}
IEnumerator LoadAssetBundleAsync(string path, string debugMessage, string assetName, string spriteName = null)
{
AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(path);
// 等待加载完成
yield return request;
var myLoadedAssetBundle = request.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.LogError("Failed to load AssetBundle: " + debugMessage);
}
else
{
Debug.Log(debugMessage + "加载完成");
if (debugMessage == "_UI_AB")
{
if (!string.IsNullOrEmpty(assetName))
{
GameObject prefab = myLoadedAssetBundle.LoadAsset<GameObject>(assetName);
GameObject Clone = Instantiate(prefab); //prefab中有Imgs图片.sprite 在spriteAtlas里面,编辑器加载的图片是正确的,但是APK加载的Imgs图片.sprite = spriteAtlas图集
Clone.transform.SetParent(Parent_);
Clone.transform.localPosition = Vector3.zero;
}
}
else if (debugMessage == "_图集_AB")
{
//用于检测该AB包中拥有的所有资源,如Atlas_One
object[] allAssets = myLoadedAssetBundle.LoadAllAssets();
foreach (var asset in allAssets)
{
Debug.Log("Asset in bundle: " + asset);
}
if (!string.IsNullOrEmpty(assetName))
{
// 从 SpriteAtlas 中获取 Sprite
SpriteAtlas spriteAtlas = myLoadedAssetBundle.LoadAsset<SpriteAtlas>(assetName);
// 获取 SpriteAtlas 中的所有 Sprite
// Sprite[] sprites = new Sprite[spriteAtlas.spriteCount];
// spriteAtlas.GetSprites(sprites);
Sprite Sp = spriteAtlas.GetSprite(spriteName);//编辑器与APK加载的话,图片显示全都没问题
IMG.sprite = Sp;
}
}
}
}
}
运行,点击Btn1 ,可以加载图片ui_frame_fight
点击Btn2,可以创建预制体Prefab_One
一如既往,还有疑问,就直接在评论区问,我会尽快回复的