unity打AB包,AssetBundle预制体与图集(二)

编程入门 行业动态 更新时间:2024-10-25 02:22:35

unity打AB包,AssetBundle预制体与<a href=https://www.elefans.com/category/jswz/34/1765399.html style=图集(二)"/>

unity打AB包,AssetBundle预制体与图集(二)

第二步:加载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_Oneobject[] allAssets = myLoadedAssetBundle.LoadAllAssets();foreach (var asset in allAssets){Debug.Log("Asset in bundle: " + asset);}if (!string.IsNullOrEmpty(assetName)){// 从 SpriteAtlas 中获取 SpriteSpriteAtlas 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

一如既往,还有疑问,就直接在评论区问,我会尽快回复的

更多推荐

unity打AB包,AssetBundle预制体与图集(二)

本文发布于:2023-11-16 09:14:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615820.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图集   unity   AB   AssetBundle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!