Unity动态加载AssetBundle

本文介绍了一个Unity脚本,用于处理资源包的加载和游戏场景的切换。通过使用AssetBundle,脚本实现了不同平台上的资源加载,包括Android、iOS、Windows和WebGL,并详细展示了如何使用WWW和UnityWebRequest两种方式进行资源加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Test2:MonoBehaviour {
    public static string BundleURL;
    private GameObject g;
    private string assetname;

    private void Awake() {
        //平台预处理
        BundleURL =
#if UNITY_ANDROID
                    "jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
                    Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
 "file://" + Application.dataPath + "/StreamingAssets/";//Test_AssetBundle 资源束文件的位置
#elif UNITY_WEBGL
 "服务器地址";
#else
                    string.Empty;  
#endif
    }

    public void OnPrefab() {
        StartCoroutine(DownPrefabAndSceneWWW(BundleURL + ".manifest名称"));
    }
    //WWW加载
    IEnumerator DownPrefabAndSceneWWW(string path) {
        //电脑端加载使用
        using (WWW asset = new WWW(path)) { 
            yield return asset;
        AssetBundle bundle = asset.assetBundle;
        //资源加载 
        //加载的是打包到资源包里面,每个资源的名字
        g = Instantiate(bundle.LoadAsset(".manifestPrefab")) as GameObject;
        g.transform.position = Vector3.zero;
        //资源加载完毕后记得Unload,不然再次加载资源的时候无法加载
        bundle.Unload(false);
        }
    }
    //UnityWebRequest加载
    IEnumerator DownPrefabAndSceneUnityWebRequest(string path) {
        using (UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url)) {
            // Debug.LogError(url);
            yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError) {
                Debug.Log(www.error);
            }
            else//第一种加载方法  需要把场景拖进buildsetting
            {
                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
                SceneManager.LoadScene(assetname);
                Debug.Log(www.GetHashCode());
                print("跳转场景");
                // AssetBundle.Unload(false),释放AssetBundle文件内存镜像,不销毁Load创建的Assets对象
                // AssetBundle.Unload(true),释放AssetBundle文件内存镜像同时销毁所有已经Load的Assets内存镜像
                bundle.Unload(false);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值