unity加载资源的四种方法

tech2025-08-14  6

前言

一 资源打包方法

1编写打包工具脚本

必须在assets目录下editor目录里子目录里 脚本

using UnityEngine; using UnityEditor; public class BuildAssetBundle : MonoBehaviour { [MenuItem("Tools/打AB包")] public static void BuildAB() { BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64); AssetDatabase.Refresh(); Debug.LogError("打包完成"); } }

2标题创建一个“StreamingAssets”文件夹(存放打包资源),然后选择给需要打包的物体添加AssetBundle标签,最后点击顶部的Tools–>打AB包稍等一下即可打出AB包,如下所示:

3点击自己写的打包工具

4打包结果

4种资源加载方法

using System.Collections; using System.Collections.Generic; using UnityEngine; namespace TestFunction { public class LoadFour : MonoBehaviour { //加载的预设物体 public GameObject _pre; void Start() { //1、资源加载的第一种方式,将预支暴露在面板中,拖拽赋值,通常不用 if (_pre != null) { //实例化预设物体 GameObject obj = Instantiate(_pre); //修改加载物体的名称 obj.name = "拖拽资源加载方式"; } //2、资源加载的第二种方式,用Resources.Load加载资源 //预设需要放置在Resources目录下面, //最大只能加载2G的资源内容,一般不建议使用 Prefabs(Resources下的目录)/Cylinder(加载预支名称) GameObject loadObj = Instantiate(Resources.Load("Prefabs/Cylinder")) as GameObject; loadObj.name = "Resources加载方式"; //3、资源加载的第三种方式,使用AssetBundle加载的方式加载(常用方式) AssetBundle assetBundleObj = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/cube"); GameObject abObj = Instantiate(assetBundleObj.LoadAsset<GameObject>("cube")); abObj.name = "AB资源加载方式"; //4、资源加载的第四种方式,使用AssetDatabase.LoadAssetAtPath加载资源(编辑器框架开发使用) "Assets/Load/资源名称"资源放置位置+名称 不需要打包 加载任意位置资源预制 GameObject DBobj = Instantiate(UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Load/bg_anchor_foodhome01.prefab")); DBobj.name = "DB资源加载方式"; } } }
最新回复(0)