Unity 底层框架篇 (二)
Unity加载资源的多种方式
1、通过变量 m_prefab 公有化 public -> 编辑器里拖入prefab-> GameObject.Instantiate(m_prefab); 不推荐
2、将资源放入Resouces文件夹(编辑器若没有这个文件夹可以自己创建,Unity会自动识别)通过GameObject.Instantiate(Resources.Load("资源路径") as GameObject) 不推荐
// 资源加载的第二种方式 注意Attack 不加后缀 GameObject obj = GameObject.Instantiate(Resources.Load("Attack") as GameObject);
Resources下的文件容量有上限 大概2G ,一般在该文件夹下 放一些配置表
3、AssetBunddle
3.1 先将资源设置AssetBundle名字

3.2、创建编辑器扩展工具脚本 (一定要在Editor文件夹下创建脚本) 内容如下:
using UnityEngine; using UnityEditor; // 因为它是放在Editor文件夹下的 所以他的程序集归属于Assembly-CSharp-Editor.dll public class MyBundleEditor { // 这些特性是归属于 Assembly-CSharp-Editor.dll 程序集里的 特性本质上就是一个函数 括号里的是参数 [MenuItem("MyTools/BuildAssetBundle")] public static void buildBundle() { // 使用BuildPipeLine /// <summary> /// <para>Build all AssetBundles specified in the editor.</para> /// </summary> /// <param name="outputPath">Output path for the AssetBundles.</param> /// <param name="assetBundleOptions">AssetBundle building options.</param> /// <param name="targetPlatform">Chosen target build platform.</param> /// <returns> /// <para>The manifest listing all AssetBundles included in this build.</para> /// </returns> //public static AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform) BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget); // 生成的文件中 .manifast文件里 保存有所有AssetBundle文件的依赖 // 重新生成资源的时候 要使用AssetDatabase去刷新一下 AssetDatabase.Refresh(); } }
3.3 点击自己编辑器上扩展的按钮 MyTools/BuildAssetBundle 生成上面设置的 asset AssetBundle包

此时生成了 AssetBundle 接下来就能去动态使用包里的内容了 AB包可以在本地 也可以在远程服务器上
// assetBundle 是一个压缩包 LoadFromFile 可以加载attack AssetBundle assetBundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/attack"); // 而Instantiate 实际上是克隆一个从assetBundle下加载出来的单个资源 GameObject a = assetBundle.LoadAsset<GameObject>("attack"); GameObject obj = GameObject.Instantiate(a);
4、AssetDataBase.LoadAtPath 它不在游戏运行时使用 它是编辑器Api
// 资源加载的第四种方式 GameObject obj = GameObject.Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>("Assets/GameData/Prefabs/Attack.prefab"));
浙公网安备 33010602011771号