Compare commits

...

166 Commits
1.0.4 ... 1.1.1

Author SHA1 Message Date
hevinci
b238759f61 Update CHANGELOG.md 2022-07-07 10:13:39 +08:00
hevinci
2bb0d18891 Update package.json 2022-07-07 10:13:20 +08:00
hevinci
7d5b6504f4 Update YooAssets.cs
检测原生文件加载方法,预防传入无效文件。
2022-07-05 20:07:32 +08:00
何冠峰
63f90e1537 Merge pull request #19 from LiuOcean/main
Fix Unity 2020 IL2Cpp UniTask Bug
2022-07-02 15:28:12 +08:00
何冠峰
65b43feb38 Merge pull request #18 from Y-way/typo
拼写错误
2022-07-02 15:27:59 +08:00
L
4f00a19344 Fix Unity 2020 IL2Cpp UniTask Bug 2022-07-02 12:33:59 +08:00
hevinci
3bfca7d340 Update AssetBundleBuilder 2022-06-30 14:29:27 +08:00
Y-way
8538d0de28 拼写错误 2022-06-30 14:09:07 +08:00
hevinci
5425e17d6f Update AssetOperationHandle.cs 2022-06-30 12:12:44 +08:00
何冠峰
bb3065d08d Merge pull request #17 from Y-way/OptimizeAssetOperationHandle
AssetOperationHandle类新增便捷方法,便于链式编程
2022-06-30 12:03:57 +08:00
hevinci
1adc3d7ed6 Update document 2022-06-30 12:02:06 +08:00
hevinci
556b23b488 Update OperationHandleBase.cs 2022-06-29 12:41:06 +08:00
hevinci
5b0c189d75 Update InitializationOperation.cs 2022-06-29 11:59:39 +08:00
hevinci
161fdff09a Update document 2022-06-29 10:02:57 +08:00
hevinci
81b3dd57b1 Update document 2022-06-28 20:23:03 +08:00
hevinci
1ab0f447d2 Update document 2022-06-28 20:20:36 +08:00
hevinci
9ac07e94d1 Update UpdateManifestOperation
增加在弱联网环境下的更新支持
2022-06-28 20:13:32 +08:00
Y-way
fee6e8f4dd 增加失败提示 2022-06-28 19:45:37 +08:00
Y-way
1e39b1af6d AssetOperationHandle类新增便捷方法,便于链式编程
TextAsset asset;
                YooAssets.LoadAssetAsync<TextAsset>(name).WaitForAsyncOperationComplete().GetAssetObjet<TextAsset>(out asset).Release();
                YooAssets.LoadAssetAsync<TextAsset>(name).Completed += handler => {
                    handler.GetAssetObjet(out asset).Release();
                };
2022-06-28 19:17:47 +08:00
hevinci
727d841d47 Update document 2022-06-28 17:18:43 +08:00
hevinci
5e0d4d6ee1 Update document 2022-06-27 14:03:14 +08:00
hevinci
32ce99949b Update AssetBundleDebugger
完善调试器窗口,增加帧数控制。
2022-06-25 17:56:49 +08:00
hevinci
fbb9bff3c7 Remove AutoReleaseGameObjectHandle param.
移除自动释放资源对象句柄的功能。
2022-06-25 12:09:20 +08:00
hevinci
6471b237ce Update Patch System
离线模式移除资内置资源解压功能。
2022-06-25 11:42:50 +08:00
hevinci
d452c610c1 Update document 2022-06-25 11:41:13 +08:00
hevinci
009fa88402 Update document 2022-06-25 10:59:51 +08:00
hevinci
6d26276352 Update AssetBundleDebuggerWindow.cs
修复了AssetView和BundleView切换失败的问题。
2022-06-24 17:03:27 +08:00
hevinci
bdca693413 Update CHANGELOG.md 2022-06-23 21:48:09 +08:00
hevinci
a2d30ca99a Update package.json 2022-06-23 21:44:32 +08:00
hevinci
5c02bc2bee Update AssetBundleCollector
增加分组禁用功能。
2022-06-23 20:41:32 +08:00
何冠峰
00ffd55fef Merge pull request #15 from JourneyHans/main
编辑器模式下打包执行成功后自动显示Bundle文件夹
2022-06-23 16:08:11 +08:00
hevinci
32148821a1 Add AutoReleaseGameObjectHandle initialize parameters
支持自动释放游戏对象句柄的功能。
2022-06-23 16:02:53 +08:00
hevinci
60f6483a86 Update AssetBundleCollector window
修复StaticAssetCollector无法预览Main Assets列表的问题。
2022-06-23 14:07:12 +08:00
hevinci
9b80300f19 Update DefaultFilterRule.cs 2022-06-23 13:58:47 +08:00
hevinci
8f02bfa3a6 Update DefaultFilterRule.cs
修复了精灵过滤器无效的问题。
2022-06-23 13:46:31 +08:00
huanghanzhi
93607ad62a 编辑器模式下打包执行成功后自动显示Bundle文件夹 2022-06-22 15:50:56 +08:00
hevinci
3cbf891674 Add GetAssetPath method.
增加YooAssets.GetAssetPath方法
2022-06-21 17:21:37 +08:00
hevinci
00688a65af Add VerifyLevel filed.
增加了下载文件校验等级初始化参数。
2022-06-21 16:04:59 +08:00
hevinci
c0099cb90c Update RawFileOperation.cs
优化原生文件加载逻辑
2022-06-21 14:08:02 +08:00
hevinci
43248408fc Update DownloaderOperation.cs
Add OnStartDownloadFileCallback filed.
Change OnDownloadFileFailedCallback to OnDownloadErrorCallback.
2022-06-21 10:40:16 +08:00
hevinci
d535500b9e Update AssetBundleDebugger 2022-06-20 19:56:19 +08:00
hevinci
9cea3e1ba9 Update YooAssets.cs
Add IsInitialized filed
2022-06-20 15:38:55 +08:00
何冠峰
746fa44ab8 Merge pull request #13 from susices/main
修复资源包收集工具页面 切换EnableAddressable时 未及时刷新收集器UI的问题
2022-06-20 10:21:20 +08:00
hevinci
b23d56f49c Update document 2022-06-20 10:19:17 +08:00
hevinci
3693f1ea98 Update AssetInfo.cs
Add Address filed.
2022-06-20 10:18:51 +08:00
susices
14127e8097 Merge branch 'tuyoogame:main' into main 2022-06-18 18:27:28 +08:00
wenchao
ad0d47bd68 修复资源包收集工具页面 切换EnableAddressable时 未及时刷新收集器UI的问题 2022-06-18 18:26:24 +08:00
hevinci
b59fb0d811 Optimize share bundle pack logic
优化了共享资源的打包逻辑。
2022-06-17 12:05:14 +08:00
hevinci
0b1990f040 Yooasset add destroy methods
增加销毁机制
2022-06-15 18:14:04 +08:00
hevinci
8deb239450 Update remote debugger
Support remote mobie device debugging
2022-06-15 16:52:54 +08:00
hevinci
33387e8d26 Update AssetBundleBuilder 2022-06-10 10:50:27 +08:00
hevinci
9d4656a1f2 Update EditorHelper.cs 2022-06-09 16:09:35 +08:00
hevinci
9c49d8d54a Update manifest operation add FoundNewManifest filed.
补丁清单更新操作,增加了查询发现了新的清单的字段。
2022-05-27 15:17:10 +08:00
hevinci
4ee6b3cdc2 Update CHANGELOG.md 2022-05-22 15:14:27 +08:00
hevinci
d5636a71b1 Update package.json 2022-05-22 15:08:45 +08:00
hevinci
b1ca47fc14 Update EditorHelper.cs 2022-05-22 15:03:40 +08:00
hevinci
ddb35620cb Update document 2022-05-22 00:40:15 +08:00
hevinci
a906a84721 Optimized the loading method of the setting file
优化了配置文件的加载方式和途径。
2022-05-22 00:39:22 +08:00
hevinci
d43d30f72f The collector window supports undo operations
资源收集界面支持撤销操作
2022-05-21 23:41:58 +08:00
hevinci
e9841a65c6 Added pause method and resume method to patch downloader
补丁下载器增加暂停方法和恢复方法
2022-05-21 22:36:06 +08:00
hevinci
2dd3ba847e Bundle build system adds builtin files copy options
资源构建增加内置文件拷贝的选项
2022-05-21 22:24:05 +08:00
hevinci
0dcbe0574c Fixed load sprite issues in editor simulate mode
修复加载精灵图片失败的问题在编辑器模拟模式下。
2022-05-16 20:16:10 +08:00
hevinci
d01dce438c Fixed window opening issues
修复了资源收集配置存在多个的时候,导致后续无法打开窗口的问题。
2022-05-16 15:48:23 +08:00
hevinci
76929cc015 Update CHANGELOG.md 2022-05-14 12:47:16 +08:00
hevinci
cde0f4bcd8 Update package.json 2022-05-14 12:47:12 +08:00
hevinci
8dc0560537 Optimized the loading method of the setting file
优化了配置文件的加载方式和途径。
2022-05-13 23:53:19 +08:00
hevinci
a054740de6 Optimize assetbundle build parameters
优化了资源包的构建参数:始终开启DisableLoadAssetByFileName
2022-05-13 21:58:23 +08:00
hevinci
029b850d6b Update asset system
新增获取所有子资源对象的方法。
2022-05-13 14:57:49 +08:00
hevinci
8260653eae Merge branch 'main' of https://github.com/tuyoogame/YooAsset 2022-05-13 14:29:36 +08:00
hevinci
bd7b9b5c44 Update README.md 2022-05-13 14:29:28 +08:00
hevinci
8f33a391f8 Update document 2022-05-13 14:29:22 +08:00
何冠峰
2f9d3a9f11 Merge pull request #11 from jiangguilong2000/main
feat(AssetSystem): 获取图集下所有的精灵对象集合
2022-05-13 14:23:23 +08:00
Allen Jiang
316294f449 feat(AssetSystem): 获取图集下所有的精灵对象集合 2022-05-13 14:08:36 +08:00
hevinci
09fac3bd64 Add warning when asset path is invalid. 2022-05-12 23:13:21 +08:00
hevinci
2da81212b4 Update document 2022-05-12 12:37:48 +08:00
hevinci
4cad587609 Optimized asset system and patch system framework
优化了资源定位不正确导致的错误报告方式。
YooAssets.ProcessOperation()重命名为YooAssets.StartOperation()
YooAssets.GetBundleInfo()已经移除方法。
YooAssets.IsNeedDownloadFromRemote()新增加方法。
2022-05-11 16:48:17 +08:00
hevinci
67eeae31c7 Update patch manifest
更新资源清单:资源对象增加分类标签。
2022-05-11 16:23:31 +08:00
hevinci
ae465a47a9 Simulate build use default build version.
模拟构建模式使用一个默认的资源版本号。
2022-05-11 16:13:51 +08:00
hevinci
23b59f6ad6 Update document 2022-05-09 22:14:49 +08:00
hevinci
09e3483e0a Update README.md 2022-05-09 22:13:20 +08:00
hevinci
b3f4e9ae6e Update document 2022-05-09 22:13:14 +08:00
hevinci
79efe6237d Update asset system 2022-05-09 21:18:15 +08:00
hevinci
bf0f479234 Update download system 2022-05-09 18:44:49 +08:00
hevinci
ece1dab28b Update README.md 2022-05-08 22:21:17 +08:00
hevinci
b913b5c20c Update document 2022-05-08 22:21:13 +08:00
hevinci
366cf3c792 Update CHANGELOG.md 2022-05-08 22:18:33 +08:00
hevinci
21ccd4d29f Update package.json 2022-05-08 22:17:57 +08:00
hevinci
b8ba4219cd Update YooAssets.cs 2022-05-08 22:09:44 +08:00
hevinci
43da6847ba Merge branch 'main' of https://github.com/tuyoogame/YooAsset 2022-05-08 21:51:35 +08:00
hevinci
c22c87e16b Update asset bundle reporter window
更新构建报告窗口:增加预览AssetBundle文件内容的功能。
2022-05-08 21:51:27 +08:00
何冠峰
4551dabb39 Merge pull request #9 from LiuOcean/main
Add AsyncOperationBaseExtensions UniTask Support
2022-05-08 19:32:27 +08:00
L
774ad0e5ef Add AsyncOperationBaseExtensions UniTask Support 2022-05-08 11:04:55 +08:00
hevinci
bd87e982ef Add progress of async operation
异步操作类增加进度查询。
2022-05-07 20:30:16 +08:00
hevinci
ecd4973948 Update editor simulate mode parameters
更新编辑器下模拟模式的初始化参数类
2022-05-07 19:20:52 +08:00
hevinci
6dd1eee6c3 Remove LoadAllAssets method.
移除YooAssets.LoadAllAssets方法。
2022-05-07 18:45:15 +08:00
hevinci
42703def02 Add process operation method.
增加开启异步操作的方法。
2022-05-07 18:23:00 +08:00
hevinci
afc08d4e46 Add load all asset method.
增加新的资源加载方法:加载资源对象所属资源包里的所有资源。
2022-05-06 23:15:03 +08:00
hevinci
65875b66c2 Optimized the speed of simulate build 2022-05-06 20:09:36 +08:00
hevinci
091758022f Update document 2022-05-06 10:00:09 +08:00
hevinci
c395a7a750 Supports location to lower
支持资源定位地址小写。
2022-05-05 23:11:26 +08:00
hevinci
2ab045658b Compatible with Unity2018
兼容Unity2018版本
2022-05-05 22:03:35 +08:00
hevinci
c196cd84d3 Optimized the speed of simulate build.
优化了编辑器下模拟构建的速度。
2022-05-05 21:12:44 +08:00
hevinci
c3c18cd555 Added initialization fault error detection
增加初始化容错检测。
2022-05-05 11:44:03 +08:00
hevinci
cb48c672bd Added version info to the collector xml config
资源收集配表增加版本信息。
2022-05-05 11:25:34 +08:00
hevinci
713073203c Fixed asset bundle collector config error
修复了资源收集器导出配置文件时没有导出公共设置。
2022-05-04 21:38:16 +08:00
hevinci
eafdb8cd31 Update AssetBundleCollector
AssetBundleGrouper变更为AssetBundleCollector
2022-05-04 21:24:51 +08:00
hevinci
d592fb96a6 Optimize collector window jank problem
优化了资源收集窗体卡顿问题。
2022-05-04 19:47:01 +08:00
hevinci
0c116b7701 Update CHANGELOG.md 2022-05-04 00:50:44 +08:00
hevinci
664bb1f71c Update CHANGELOG.md 2022-05-04 00:45:21 +08:00
hevinci
5f809cc26a Update package.json 2022-05-04 00:44:54 +08:00
hevinci
1bb70edd4b Update document 2022-05-04 00:12:06 +08:00
hevinci
2922b44747 Update document 2022-05-03 22:29:01 +08:00
hevinci
f34078a604 The report window supports sorting
报告浏览窗口支持排序
2022-05-03 22:12:59 +08:00
hevinci
1c1bb078b1 Remove auto release interval create param.
移除了自动释放资源的初始化参数。
2022-05-03 12:33:28 +08:00
hevinci
9ec841ff67 Add get asset info method.
增加获取资源信息的方法。
2022-05-03 12:23:08 +08:00
hevinci
665a16fe60 Support fast build mode.
支持快速构建模式,真实的实现EditorPlayMode的运行时环境。
2022-05-02 23:15:09 +08:00
hevinci
8d02406211 Update AssetSystem 2022-05-02 17:54:55 +08:00
hevinci
873d873194 Add clear unused cache files method.
增加清空缓存文件的方法。
2022-05-02 15:03:36 +08:00
hevinci
2c9819762a Update package update method 2022-05-01 20:43:00 +08:00
hevinci
ce70eebda6 Add package update method
新增指定资源版本的资源更新下载方法。
2022-05-01 20:33:50 +08:00
hevinci
47af58bb5b Patch DownLoader added a method to download all resources.
补丁下载器新增下载全部资源的方法。
2022-05-01 15:26:48 +08:00
hevinci
b0397981ce Delete the file whose verification failed
初始化的时候,删除验证失败的资源文件。
2022-05-01 14:47:59 +08:00
hevinci
650d8689ee Optimize packaging bundle core logic
优化了打包的核心逻辑,支持设置依赖资源收集器。
2022-04-30 23:14:20 +08:00
hevinci
b443a1c308 Optimize packaging bundle core logic
优化了打包的核心逻辑,对依赖资源进行自动划分。
2022-04-30 19:10:52 +08:00
hevinci
b1bb79bd95 Update README.md 2022-04-29 18:31:24 +08:00
hevinci
7ca1ebac79 Update document 2022-04-29 18:31:22 +08:00
hevinci
f8036782e4 BundleInfo Adds the InCloud method
BundleInfo增加资源包文件是否在云端的查询接口
2022-04-29 16:42:53 +08:00
hevinci
ca7b42981b Fixed operation system error
修复异步操作系统的Task二次等待失败的问题。
2022-04-29 11:14:21 +08:00
hevinci
c6440c9312 Update AssetBundleGrouper 2022-04-29 10:46:38 +08:00
hevinci
3de44a416c YooAssetSetting folder search location
YooAssetSetting文件夹全路径搜索定位
2022-04-28 23:29:15 +08:00
hevinci
62f1c050ca Rename LoadRawFileAsync to GetRawFileAsync
LoadRawFileAsync 方法重新命名为GetRawFileAsync
2022-04-28 22:49:55 +08:00
hevinci
6070e619da Update editor window 2022-04-28 22:45:28 +08:00
hevinci
636fbed7f2 Add new pack rule
增加一个新的打包规则:收集器目录下顶级文件夹收集器
2022-04-28 22:16:34 +08:00
hevinci
d354db382c Update document 2022-04-28 19:25:14 +08:00
hevinci
501765eaa7 Update ShaderVariantCollector
着色器变种收集工具支持配置缓存
2022-04-28 18:32:10 +08:00
hevinci
9f1eaf4a62 Update adressable location 2022-04-28 18:28:46 +08:00
何冠峰
a4b098084d Merge pull request #7 from LiuOcean/main
后续打开的窗口会自动找到 YooAsset 已存在的 Window Dock
2022-04-28 17:43:59 +08:00
hevinci
2cb006f3d9 Support addressable location
支持可寻址资源定位
2022-04-28 17:23:31 +08:00
hevinci
775c724840 Update AssetBundleBuilder
AssetBundleBuilder界面增加演练构建选项。
构建文件名增加版本信息。
2022-04-27 11:02:30 +08:00
hevinci
15dc047488 Update CHANGELOG.md 2022-04-26 21:24:12 +08:00
hevinci
91b25400dc Update package.json 2022-04-26 21:24:03 +08:00
L
9b3839ac0b Merge branch 'main' of ssh://github.com/LiuOcean/YooAsset 2022-04-26 19:41:12 +08:00
L
ff74dcdd8b All YooAsset Window Auto Dock 2022-04-26 19:41:06 +08:00
hevinci
d316c5000a Merge branch 'main' of https://github.com/tuyoogame/YooAsset 2022-04-26 19:14:25 +08:00
hevinci
d8692c836f Update document 2022-04-26 19:14:22 +08:00
何冠峰
0a4a3d8f2e Merge pull request #6 from LiuOcean/main
Add Group Window Undo Redo
2022-04-26 19:13:04 +08:00
hevinci
5484b604a7 Optimize class type search code
优化类型搜索方式,改为全域搜索类型。
2022-04-26 18:24:14 +08:00
L
66c3c4862a Add Group Window Undo Redo 2022-04-26 12:48:24 +08:00
何冠峰
e9d31bbf94 Merge pull request #5 from LiuOcean/main
Add UniTask Support
2022-04-26 10:15:02 +08:00
L
55bcd502e2 Add UniTask Support 2022-04-25 15:35:11 +08:00
hevinci
9bf22f2c79 Operation handles support error queries
操作句柄支持错误信息查询。
2022-04-24 18:30:35 +08:00
hevinci
cbf142dbf8 Fixed editor window display exception at unity2021
修复工具界面显示异常在Unity2021版本下。
2022-04-24 13:11:19 +08:00
hevinci
a6e94acefb Update AssemblyInfo.cs 2022-04-24 11:16:38 +08:00
hevinci
469d73d641 Update CHANGELOG.md 2022-04-22 18:16:31 +08:00
hevinci
0d521c68bd Update package.json 2022-04-22 18:16:25 +08:00
hevinci
cd62c1dd9a Update AssetSystem 2022-04-22 16:43:09 +08:00
hevinci
e6422445a6 Added debugging information
新增调试信息,出生场景和出生时间。
2022-04-22 16:22:09 +08:00
hevinci
7683746032 Support do a dry run build.
支持演练构建模式。
2022-04-22 15:14:37 +08:00
hevinci
a25fd19bcc Fixed an issue with task asyn loading waiting 2022-04-21 21:55:48 +08:00
hevinci
6675e8f171 Fixed an issue with task asyn loading waiting 2022-04-21 21:39:00 +08:00
hevinci
c836dce54d Fixed an issue with task asyn loading waiting
修复Task异步加载一直等待的问题。
2022-04-21 21:27:53 +08:00
hevinci
f3ab8f63e7 Optimize the scene unload logic.
优化场景卸载逻辑,在加载新的主场景的时候自动卸载已经加载的所有场景。
2022-04-21 21:11:11 +08:00
hevinci
20d2c517b2 Optimized raw file load logic
优化原生文件加载逻辑,支持离线运行模式和编辑器运行模式。
2022-04-21 16:16:40 +08:00
hevinci
d6a2b31d5c Add editor extend properties
增加编辑器扩展的支持
2022-04-19 10:11:24 +08:00
hevinci
533f96361a Update AssetBundleWindow
修复了非主动收集的着色器没有打进统一的着色器资源包的问题。
修复了单个收集的资源对象没有设置依赖资源列表的问题。
资源打包的过滤文件列表增加cginc格式。
2022-04-18 19:48:37 +08:00
hevinci
09807901c0 Update README.md 2022-04-18 16:01:48 +08:00
235 changed files with 9031 additions and 3750 deletions

View File

@@ -0,0 +1,145 @@
using System;
using YooAsset;
using static Cysharp.Threading.Tasks.Internal.Error;
namespace Cysharp.Threading.Tasks
{
public static class AsyncOperationBaseExtensions
{
public static UniTask.Awaiter GetAwaiter(this AsyncOperationBase handle)
{
return ToUniTask(handle).GetAwaiter();
}
public static UniTask ToUniTask(this AsyncOperationBase handle,
IProgress<float> progress = null,
PlayerLoopTiming timing = PlayerLoopTiming.Update)
{
ThrowArgumentNullException(handle, nameof(handle));
if(handle.IsDone)
{
return UniTask.CompletedTask;
}
return new UniTask(
AsyncOperationBaserConfiguredSource.Create(
handle,
timing,
progress,
out var token
),
token
);
}
sealed class AsyncOperationBaserConfiguredSource : IUniTaskSource,
IPlayerLoopItem,
ITaskPoolNode<AsyncOperationBaserConfiguredSource>
{
private static TaskPool<AsyncOperationBaserConfiguredSource> pool;
private AsyncOperationBaserConfiguredSource nextNode;
public ref AsyncOperationBaserConfiguredSource NextNode => ref nextNode;
static AsyncOperationBaserConfiguredSource()
{
TaskPool.RegisterSizeGetter(typeof(AsyncOperationBaserConfiguredSource), () => pool.Size);
}
private readonly Action<AsyncOperationBase> continuationAction;
private AsyncOperationBase handle;
private IProgress<float> progress;
private bool completed;
private UniTaskCompletionSourceCore<AsyncUnit> core;
AsyncOperationBaserConfiguredSource() { continuationAction = Continuation; }
public static IUniTaskSource Create(AsyncOperationBase handle,
PlayerLoopTiming timing,
IProgress<float> progress,
out short token)
{
if(!pool.TryPop(out var result))
{
result = new AsyncOperationBaserConfiguredSource();
}
result.handle = handle;
result.progress = progress;
result.completed = false;
TaskTracker.TrackActiveTask(result, 3);
if(progress != null)
{
PlayerLoopHelper.AddAction(timing, result);
}
handle.Completed += result.continuationAction;
token = result.core.Version;
return result;
}
private void Continuation(AsyncOperationBase _)
{
handle.Completed -= continuationAction;
if(completed)
{
TryReturn();
}
else
{
completed = true;
if(handle.Status == EOperationStatus.Failed)
{
core.TrySetException(new Exception(handle.Error));
}
else
{
core.TrySetResult(AsyncUnit.Default);
}
}
}
bool TryReturn()
{
TaskTracker.RemoveTracking(this);
core.Reset();
handle = default;
progress = default;
return pool.TryPush(this);
}
public UniTaskStatus GetStatus(short token) => core.GetStatus(token);
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
public void GetResult(short token) { core.GetResult(token); }
public UniTaskStatus UnsafeGetStatus() => core.UnsafeGetStatus();
public bool MoveNext()
{
if(completed)
{
TryReturn();
return false;
}
if(!handle.IsDone)
{
progress?.Report(handle.Progress);
}
return true;
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2cceff5ec1f84bd0a6a9b4ed7719527c
timeCreated: 1651978895

View File

@@ -0,0 +1,215 @@
#if UNITY_2020_1_OR_NEWER && ! UNITY_2021
#define UNITY_2020_BUG
#endif
using System;
using System.Runtime.CompilerServices;
using YooAsset;
using static Cysharp.Threading.Tasks.Internal.Error;
namespace Cysharp.Threading.Tasks
{
public static class OperationHandleBaseExtensions
{
public static UniTask.Awaiter GetAwaiter(this OperationHandleBase handle)
{
return ToUniTask(handle).GetAwaiter();
}
public static UniTask ToUniTask(this OperationHandleBase handle,
IProgress<float> progress = null,
PlayerLoopTiming timing = PlayerLoopTiming.Update)
{
ThrowArgumentNullException(handle, nameof(handle));
if(!handle.IsValid)
{
return UniTask.CompletedTask;
}
return new UniTask(
OperationHandleBaserConfiguredSource.Create(
handle,
timing,
progress,
out var token
),
token
);
}
sealed class OperationHandleBaserConfiguredSource : IUniTaskSource,
IPlayerLoopItem,
ITaskPoolNode<OperationHandleBaserConfiguredSource>
{
private static TaskPool<OperationHandleBaserConfiguredSource> pool;
private OperationHandleBaserConfiguredSource nextNode;
public ref OperationHandleBaserConfiguredSource NextNode => ref nextNode;
static OperationHandleBaserConfiguredSource()
{
TaskPool.RegisterSizeGetter(typeof(OperationHandleBaserConfiguredSource), () => pool.Size);
}
private readonly Action<OperationHandleBase> continuationAction;
private OperationHandleBase handle;
private IProgress<float> progress;
private bool completed;
private UniTaskCompletionSourceCore<AsyncUnit> core;
OperationHandleBaserConfiguredSource() { continuationAction = Continuation; }
public static IUniTaskSource Create(OperationHandleBase handle,
PlayerLoopTiming timing,
IProgress<float> progress,
out short token)
{
if(!pool.TryPop(out var result))
{
result = new OperationHandleBaserConfiguredSource();
}
result.handle = handle;
result.progress = progress;
result.completed = false;
TaskTracker.TrackActiveTask(result, 3);
if(progress != null)
{
PlayerLoopHelper.AddAction(timing, result);
}
// BUG 在 Unity 2020.3.36 版本测试中, IL2Cpp 会报 如下错误
// BUG ArgumentException: Incompatible Delegate Types. First is System.Action`1[[YooAsset.AssetOperationHandle, YooAsset, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] second is System.Action`1[[YooAsset.OperationHandleBase, YooAsset, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
// BUG 也可能报的是 Action '1' Action '1' 的 InvalidCastException
// BUG 此处不得不这么修改, 如果后续 Unity 修复了这个问题, 可以恢复之前的写法
#if UNITY_2020_BUG
switch(handle)
{
case AssetOperationHandle asset_handle:
asset_handle.Completed += result.AssetContinuation;
break;
case SceneOperationHandle scene_handle:
scene_handle.Completed += result.SceneContinuation;
break;
case SubAssetsOperationHandle sub_asset_handle:
sub_asset_handle.Completed += result.SubContinuation;
break;
}
#else
switch(handle)
{
case AssetOperationHandle asset_handle:
asset_handle.Completed += result.continuationAction;
break;
case SceneOperationHandle scene_handle:
scene_handle.Completed += result.continuationAction;
break;
case SubAssetsOperationHandle sub_asset_handle:
sub_asset_handle.Completed += result.continuationAction;
break;
}
#endif
token = result.core.Version;
return result;
}
#if UNITY_2020_BUG
private void AssetContinuation(AssetOperationHandle handle)
{
handle.Completed -= AssetContinuation;
BaseContinuation();
}
private void SceneContinuation(SceneOperationHandle handle)
{
handle.Completed -= SceneContinuation;
BaseContinuation();
}
private void SubContinuation(SubAssetsOperationHandle handle)
{
handle.Completed -= SubContinuation;
BaseContinuation();
}
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void BaseContinuation()
{
if(completed)
{
TryReturn();
}
else
{
completed = true;
if(handle.Status == EOperationStatus.Failed)
{
core.TrySetException(new Exception(handle.LastError));
}
else
{
core.TrySetResult(AsyncUnit.Default);
}
}
}
private void Continuation(OperationHandleBase _)
{
switch(handle)
{
case AssetOperationHandle asset_handle:
asset_handle.Completed -= continuationAction;
break;
case SceneOperationHandle scene_handle:
scene_handle.Completed -= continuationAction;
break;
case SubAssetsOperationHandle sub_asset_handle:
sub_asset_handle.Completed -= continuationAction;
break;
}
BaseContinuation();
}
bool TryReturn()
{
TaskTracker.RemoveTracking(this);
core.Reset();
handle = default;
progress = default;
return pool.TryPush(this);
}
public UniTaskStatus GetStatus(short token) => core.GetStatus(token);
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
public void GetResult(short token) { core.GetResult(token); }
public UniTaskStatus UnsafeGetStatus() => core.UnsafeGetStatus();
public bool MoveNext()
{
if(completed)
{
TryReturn();
return false;
}
if(handle.IsValid)
{
progress?.Report(handle.Progress);
}
return true;
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e1c9a3a6de2246bf88547a6b59b99b9f
timeCreated: 1650851321

View File

@@ -0,0 +1,19 @@
# UniTask 扩展
[仓库链接](https://github.com/Cysharp/UniTask)
- 请去下载对应的源码,并删除此目录最后的波浪线
- 在 UniTask `_InternalVisibleTo.cs` 文件中增加 `[assembly: InternalsVisibleTo("UniTask.YooAsset")]` 后即可使用
## 代码示例
```csharp
var handle = YooAssets.LoadAssetAsync<GameObject>("Assets/Res/Prefabs/TestImg.prefab");
await handle.ToUniTask();
var obj = handle.AssetObject as GameObject;
var go = Instantiate(obj, transform);
go.transform.localPosition = Vector3.zero;
go.transform.localScale = Vector3.one;
```

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6375cc739b170490fbc6c38181b2c600
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,17 @@
{
"name": "UniTask.YooAsset",
"rootNamespace": "",
"references": [
"GUID:e34a5702dd353724aa315fb8011f08c3",
"GUID:f51ebe6a0ceec4240a699833d6309b23"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: cf4f1d4730c114c48ab680458e5a2455
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,6 +1,287 @@
# CHANGELOG
All notable changes to this package will be documented in this file.
All notable changes to this package will be documented in this file.
## [1.1.1] - 2022-07-07
### Fixed
- 修复了AssetBundleDebugger窗口View下拉页签切换无效的问题。
- 修复了在Unity2020.3版本下UniTask在真机上的一个IL2CPP相关的错误。
### Changed
- 优化了AssetBundleDebugger窗口增加了帧数显示以及回放功能。
- 优化了AssetBundleBuilder的代码结构。
- 增强了YooAssets.GetRawFileAsync()方法的容错。
### Added
- 新增了OperationHandleBase.GetAssetInfo()方法。
````c#
/// <summary>
/// 获取资源信息
/// </summary>
public AssetInfo GetAssetInfo();
````
- 新增了AssetOperationHandle.GetAssetObjet<TAsset>()方法。
````c#
/// <summary>
/// 获取资源对象
/// </summary>
/// <typeparam name="TAsset">资源类型</typeparam>
public TAsset GetAssetObjet<TAsset>()
````
- 新增了弱联网情况下加载补丁清单方法。
````c#
/// <summary>
/// 弱联网情况下加载补丁清单
/// 注意:当指定版本内容验证失败后会返回失败。
/// </summary>
/// <param name="resourceVersion">指定的资源版本</param>
public static UpdateManifestOperation WeaklyUpdateManifestAsync(int resourceVersion)
````
### Removed
- 离线运行模式OfflinePlayMode下移除了资内置资源解压相关逻辑。
- 移除了初始化参数AutoReleaseGameObjectHandle及相关代码逻辑。
## [1.1.0] - 2022-06-23
### Fixed
- 修复了AssetBundleCollector窗口在切换EnableAddressable时未及时刷新界面的问题。
- 修复了AssetBundleCollector窗口资源过滤器CollectSprite无效的问题。
- 修复了AssetBundleCollector窗口无法正常预览StaticAssetCollector的资源列表的问题。
- 修复了在离线模式下原生文件每次都从包内加载的问题。
### Changed
- 变更了共享资源打包机制。
- AssetBundleCollector窗口增加了分组禁用功能。
- AssetBundleDebugger窗口增加了真机远程调试功能。
- AssetBundleBuilder窗口在构建成功后自动显示构建文件夹。
- DownloaderOperation.OnDownloadFileFailedCallback委托变更为OnDownloadErrorCallback委托。
### Added
- 新增UpdateManifestOperation.FoundNewManifest字段。
- 新增DownloaderOperation.OnStartDownloadFileCallback委托。
- 新增AssetInfo.Address字段。
- 新增YooAssets.IsInitialized字段。
- 新增YooAssets初始化参数。
````c#
/// <summary>
/// 下载文件校验等级
/// </summary>
public EVerifyLevel VerifyLevel = EVerifyLevel.High;
````
- 新增YooAssets获取资源完成路径的方法。
````c#
/// <summary>
/// 获取资源路径
/// </summary>
/// <param name="location">资源的定位地址</param>
/// <returns>如果location地址无效则返回空字符串</returns>
public static string GetAssetPath(string location);
````
- 新增YooAssets初始化参数。
```c#
/// <summary>
/// 自动释放游戏对象所属资源句柄
/// 说明:通过资源句柄实例化的游戏对象在销毁之后,会自动释放所属资源句柄。
/// </summary>
public bool AutoReleaseGameObjectHandle = false;
```
## [1.0.10] - 2022-05-22
### Fixed
- 修复了资源收集配置存在多个的时候,导致后续无法打开窗口的问题。
- 修复了在编辑器模拟模式下加载精灵图片失败的问题。
- 修复了在Unity2019版本无法识别配置文件的问题。
### Changed
- 资源构建增加内置资源文件(首包资源文件)拷贝的选项。
- 补丁下载器增加暂停方法和恢复方法。
- 在资源收集界面对Collector的增加和删除支持撤销和恢复操作。
## [1.0.9] - 2022-05-14
### Fixed
- 修复了YooAssets.GetAssetInfos(string Tag)方法返回了无关的资源信息的问题。
### Changed
- 编辑器下的模拟运行模式,不再依赖配置里的构建版本。
- 更新资源清单结构,资源对象类增加分类标签。
- 优化了资源工具相关配置文件的加载方式和途径,这些配置文件可以放置在任何目录下。
- 优化了Location无效后的错误报告方式。
- 优化了资源包的构建参数现在始终开启DisableLoadAssetByFileName帮助减小运行时的内存。
- YooAssets.ProcessOperation()重命名为YooAssets.StartOperation()
### Added
- 新增YooAssets.IsNeedDownloadFromRemote()方法。
````c#
public static bool IsNeedDownloadFromRemote(string location);
````
- 新增获取所有子资源对象的方法。
````c#
class SubAssetsOperationHandle
{
public TObject[] GetSubAssetObjects<TObject>();
}
````
### Removed
- YooAssets.GetBundleInfo()方法已经移除。
## [1.0.8] - 2022-05-08
### Fixed
- 修复了资源收集器导出配置文件时没有导出公共设置。
- 修复了不兼容Unity2018版本的错误。
### Changed
- AssetBundleGrouper窗口变更为AssetBundleCollector窗口。
- **优化了编辑器下模拟运行的初始化速度**。
- **优化了资源收集窗口打开时卡顿的问题**。
- 资源收集XML配表支持版本兼容。
- 资源报告查看窗口支持预览AssetBundle文件内容的功能。
- 完善了对UniTask的支持。
- YooAssets所有接口支持初始化容错检测。
### Added
- 异步操作类增加进度查询字段。
```c#
class AsyncOperationBase
{
/// <summary>
/// 处理进度
/// </summary>
public float Progress { get; protected set; }
}
```
- 增加开启异步操作的方法。
```c#
/// <summary>
/// 开启一个异步操作
/// </summary>
/// <param name="operation">异步操作对象</param>
public static void ProcessOperaiton(GameAsyncOperation operation)
```
- 新增编辑器下模拟模式的初始化参数。
````c#
/// <summary>
/// 用于模拟运行的资源清单路径
/// 注意:如果路径为空,会自动重新构建补丁清单。
/// </summary>
public string SimulatePatchManifestPath;
````
- 新增通用的初始化参数。
```c#
/// <summary>
/// 资源定位地址大小写不敏感
/// </summary>
public bool LocationToLower = false;
```
## [1.0.7] - 2022-05-04
### Fixed
- 修复了异步操作系统的Task再次等待无效的问题。
### Changed
- YooAssets.LoadRawFileAsync()方法重新命名为YooAssets.GetRawFileAsync()
- YooAssetSetting文件夹支持了全路径搜索定位。
- 优化了打包的核心逻辑,对依赖资源进行自动划分,以及支持设置依赖资源收集器。
- 初始化的时候,删除验证失败的资源文件。
- 构建报告浏览窗口支持排序功能。
- 着色器变种收集工具支持了配置缓存。
### Added
- 支持可寻址资源定位系统,包括编辑器和运行时环境。
- 增加快速构建模式用于EditorPlayMode完美模拟线上环境。
- 增加了Window Dock功能已打开的界面会自动停靠在一个窗体下。
- 增加一个新的打包规则PackTopDirectory。
- 增加获取资源信息的方法。
```c#
public static AssetInfo[] GetAssetInfos(string tag)
```
- 增加补丁下载器下载全部资源的方法。
```c#
public static PatchDownloaderOperation CreatePatchDownloader(int downloadingMaxNumber, int failedTryAgain)
```
- 增加指定资源版本的资源更新下载方法。
```c#
public static UpdatePackageOperation UpdatePackageAsync(int resourceVersion, int timeout = 60)
```
### Removed
- 移除了自动释放资源的初始化参数。
## [1.0.6] - 2022-04-26
### Fixed
- 修复工具界面显示异常在Unity2021版本下。
### Changed
- 操作句柄支持错误信息查询。
- 支持UniTask异步操作库。
- 优化类型搜索方式,改为全域搜索类型。
- AssetBundleGrouper窗口添加和移除Grouper支持操作回退。
## [1.0.5] - 2022-04-22
### Fixed
- 修复了非主动收集的着色器没有打进统一的着色器资源包的问题。
- 修复了单个收集的资源对象没有设置依赖资源列表的问题。
- 修复Task异步加载一直等待的问题。
### Changed
- 资源打包的过滤文件列表增加cginc格式。
- 增加编辑器扩展的支持第三方实现YooAsset插件。
- 优化原生文件加载逻辑,支持离线运行模式和编辑器运行模式。
- 优化场景卸载逻辑,在加载新的主场景的时候自动卸载已经加载的所有场景。
- 支持演练构建模式,在不生成资源包的情况下快速构建查看结果。
- 新增调试信息,出生场景和出生时间。
## [1.0.4] - 2022-04-18

View File

@@ -8,86 +8,6 @@ namespace YooAsset.Editor
{
public class AssetBundleBuilder
{
public class BuildParametersContext : IContextObject
{
private readonly System.Diagnostics.Stopwatch _buildWatch = new System.Diagnostics.Stopwatch();
/// <summary>
/// 构建参数
/// </summary>
public BuildParameters Parameters { private set; get; }
/// <summary>
/// 构建管线的输出目录
/// </summary>
public string PipelineOutputDirectory { private set; get; }
public BuildParametersContext(BuildParameters parameters)
{
Parameters = parameters;
PipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(parameters.OutputRoot, parameters.BuildTarget);
}
/// <summary>
/// 获取本次构建的补丁目录
/// </summary>
public string GetPackageDirectory()
{
return $"{Parameters.OutputRoot}/{Parameters.BuildTarget}/{Parameters.BuildVersion}";
}
/// <summary>
/// 获取构建选项
/// </summary>
public BuildAssetBundleOptions GetPipelineBuildOptions()
{
// For the new build system, unity always need BuildAssetBundleOptions.CollectDependencies and BuildAssetBundleOptions.DeterministicAssetBundle
// 除非设置ForceRebuildAssetBundle标记否则会进行增量打包
BuildAssetBundleOptions opt = BuildAssetBundleOptions.None;
opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it.
if (Parameters.CompressOption == ECompressOption.Uncompressed)
opt |= BuildAssetBundleOptions.UncompressedAssetBundle;
else if (Parameters.CompressOption == ECompressOption.LZ4)
opt |= BuildAssetBundleOptions.ChunkBasedCompression;
if (Parameters.ForceRebuild)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (Parameters.AppendHash)
opt |= BuildAssetBundleOptions.AppendHashToAssetBundleName; //Append the hash to the assetBundle name
if (Parameters.DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (Parameters.IgnoreTypeTreeChanges)
opt |= BuildAssetBundleOptions.IgnoreTypeTreeChanges; //Ignore the type tree changes when doing the incremental build check.
if (Parameters.DisableLoadAssetByFileName)
{
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileName; //Disables Asset Bundle LoadAsset by file name.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
}
return opt;
}
/// <summary>
/// 获取构建的耗时(单位:秒)
/// </summary>
public int GetBuildingSeconds()
{
int seconds = (int)(_buildWatch.ElapsedMilliseconds / 1000);
return seconds;
}
public void BeginWatch()
{
_buildWatch.Start();
}
public void StopWatch()
{
_buildWatch.Stop();
}
}
private readonly BuildContext _buildContext = new BuildContext();
/// <summary>
@@ -107,7 +27,8 @@ namespace YooAsset.Editor
{
new TaskPrepare(), //前期准备工作
new TaskGetBuildMap(), //获取构建列表
new TaskBuilding(), //开始执行构建
new TaskBuilding(), //开始执行构建
new TaskVerifyBuildResult(), //验证构建结果
new TaskEncryption(), //加密资源文件
new TaskCreatePatchManifest(), //创建清单文件
new TaskCreateReport(), //创建报告文件
@@ -115,11 +36,16 @@ namespace YooAsset.Editor
new TaskCopyBuildinFiles(), //拷贝内置文件
};
if (buildParameters.BuildMode == EBuildMode.SimulateBuild)
BuildRunner.EnableLog = false;
else
BuildRunner.EnableLog = true;
bool succeed = BuildRunner.Run(pipeline, _buildContext);
if (succeed)
Debug.Log($"构建成功!");
Debug.Log($"{buildParameters.BuildMode} pipeline build succeed !");
else
Debug.LogWarning($"构建失败!");
Debug.LogWarning($"{buildParameters.BuildMode} pipeline build failed !");
return succeed;
}
}

View File

@@ -10,6 +10,16 @@ namespace YooAsset.Editor
/// </summary>
public int BuildVersion = 0;
/// <summary>
/// 构建模式
/// </summary>
public EBuildMode BuildMode = EBuildMode.ForceRebuild;
/// <summary>
/// 内置资源标签(首包资源标签)
/// </summary>
public string BuildTags = string.Empty;
/// <summary>
/// 压缩方式
/// </summary>
@@ -24,15 +34,5 @@ namespace YooAsset.Editor
/// 附加后缀格式
/// </summary>
public bool AppendExtension = false;
/// <summary>
/// 强制构建
/// </summary>
public bool ForceRebuild = false;
/// <summary>
/// 内置标签
/// </summary>
public string BuildTags = string.Empty;
}
}

View File

@@ -24,21 +24,7 @@ namespace YooAsset.Editor
/// </summary>
private static void LoadSettingData()
{
// 加载配置文件
_setting = AssetDatabase.LoadAssetAtPath<AssetBundleBuilderSetting>(EditorDefine.AssetBundleBuilderSettingFilePath);
if (_setting == null)
{
Debug.LogWarning($"Create new {nameof(AssetBundleBuilderSetting)}.asset : {EditorDefine.AssetBundleBuilderSettingFilePath}");
_setting = ScriptableObject.CreateInstance<AssetBundleBuilderSetting>();
EditorTools.CreateFileDirectory(EditorDefine.AssetBundleBuilderSettingFilePath);
AssetDatabase.CreateAsset(Setting, EditorDefine.AssetBundleBuilderSettingFilePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
else
{
Debug.Log($"Load {nameof(AssetBundleBuilderSetting)}.asset ok");
}
_setting = EditorHelper.LoadSettingData<AssetBundleBuilderSetting>();
}
/// <summary>

View File

@@ -14,8 +14,7 @@ namespace YooAsset.Editor
[MenuItem("YooAsset/AssetBundle Builder", false, 102)]
public static void ShowExample()
{
AssetBundleBuilderWindow window = GetWindow<AssetBundleBuilderWindow>();
window.titleContent = new GUIContent("资源包构建工具");
AssetBundleBuilderWindow window = GetWindow<AssetBundleBuilderWindow>("资源包构建工具", true, EditorDefine.DockedWindowTypes);
window.minSize = new Vector2(800, 600);
}
@@ -23,32 +22,27 @@ namespace YooAsset.Editor
private List<Type> _encryptionServicesClassTypes;
private List<string> _encryptionServicesClassNames;
private TextField _buildOutputTxt;
private TextField _buildOutputField;
private IntegerField _buildVersionField;
private EnumField _compressionField;
private EnumField _buildModeField;
private TextField _buildinTagsField;
private PopupField<string> _encryptionField;
private EnumField _compressionField;
private Toggle _appendExtensionToggle;
private Toggle _forceRebuildToggle;
private TextField _buildTagsTxt;
public void CreateGUI()
{
VisualElement root = this.rootVisualElement;
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleBuilder/{nameof(AssetBundleBuilderWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleBuilderWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
try
{
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleBuilderWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
_buildTarget = EditorUserBuildSettings.activeBuildTarget;
_encryptionServicesClassTypes = GetEncryptionServicesClassTypes();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList();
@@ -56,9 +50,9 @@ namespace YooAsset.Editor
// 输出目录
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(defaultOutputRoot, _buildTarget);
_buildOutputTxt = root.Q<TextField>("BuildOutput");
_buildOutputTxt.SetValueWithoutNotify(pipelineOutputDirectory);
_buildOutputTxt.SetEnabled(false);
_buildOutputField = root.Q<TextField>("BuildOutput");
_buildOutputField.SetValueWithoutNotify(pipelineOutputDirectory);
_buildOutputField.SetEnabled(false);
// 构建版本
_buildVersionField = root.Q<IntegerField>("BuildVersion");
@@ -68,29 +62,30 @@ namespace YooAsset.Editor
AssetBundleBuilderSettingData.Setting.BuildVersion = _buildVersionField.value;
});
// 压缩方
_compressionField = root.Q<EnumField>("Compression");
_compressionField.Init(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.style.width = 300;
_compressionField.RegisterValueChangedCallback(evt =>
// 构建模
_buildModeField = root.Q<EnumField>("BuildMode");
_buildModeField.Init(AssetBundleBuilderSettingData.Setting.BuildMode);
_buildModeField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildMode);
_buildModeField.style.width = 300;
_buildModeField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.Setting.CompressOption = (ECompressOption)_compressionField.value;
AssetBundleBuilderSettingData.Setting.BuildMode = (EBuildMode)_buildModeField.value;
RefreshWindow();
});
// 内置资源标签
_buildinTagsField = root.Q<TextField>("BuildinTags");
_buildinTagsField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildTags);
_buildinTagsField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.Setting.BuildTags = _buildinTagsField.value;
});
// 加密方法
var encryptionContainer = root.Q("EncryptionContainer");
if (_encryptionServicesClassNames.Count > 0)
{
int defaultIndex = 0;
for (int index = 0; index < _encryptionServicesClassNames.Count; index++)
{
if (_encryptionServicesClassNames[index] == AssetBundleBuilderSettingData.Setting.EncyptionClassName)
{
defaultIndex = index;
break;
}
}
int defaultIndex = GetEncryptionDefaultIndex(AssetBundleBuilderSettingData.Setting.EncyptionClassName);
_encryptionField = new PopupField<string>(_encryptionServicesClassNames, defaultIndex);
_encryptionField.label = "Encryption";
_encryptionField.style.width = 300;
@@ -108,6 +103,16 @@ namespace YooAsset.Editor
encryptionContainer.Add(_encryptionField);
}
// 压缩方式
_compressionField = root.Q<EnumField>("Compression");
_compressionField.Init(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.style.width = 300;
_compressionField.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.Setting.CompressOption = (ECompressOption)_compressionField.value;
});
// 附加后缀格式
_appendExtensionToggle = root.Q<Toggle>("AppendExtension");
_appendExtensionToggle.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.AppendExtension);
@@ -116,27 +121,11 @@ namespace YooAsset.Editor
AssetBundleBuilderSettingData.Setting.AppendExtension = _appendExtensionToggle.value;
});
// 强制构建
_forceRebuildToggle = root.Q<Toggle>("ForceRebuild");
_forceRebuildToggle.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.ForceRebuild);
_forceRebuildToggle.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.Setting.ForceRebuild = _forceRebuildToggle.value;
_buildTagsTxt.SetEnabled(_forceRebuildToggle.value);
});
// 内置标签
_buildTagsTxt = root.Q<TextField>("BuildinTags");
_buildTagsTxt.SetEnabled(_forceRebuildToggle.value);
_buildTagsTxt.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildTags);
_buildTagsTxt.RegisterValueChangedCallback(evt =>
{
AssetBundleBuilderSettingData.Setting.BuildTags = _buildTagsTxt.value;
});
// 构建按钮
var buildButton = root.Q<Button>("Build");
buildButton.clicked += BuildButton_clicked; ;
RefreshWindow();
}
catch (Exception e)
{
@@ -148,21 +137,19 @@ namespace YooAsset.Editor
AssetBundleBuilderSettingData.SaveFile();
}
private void RefreshWindow()
{
var buildMode = AssetBundleBuilderSettingData.Setting.BuildMode;
bool enableElement = buildMode == EBuildMode.ForceRebuild;
_buildinTagsField.SetEnabled(enableElement);
_encryptionField.SetEnabled(enableElement);
_compressionField.SetEnabled(enableElement);
_appendExtensionToggle.SetEnabled(enableElement);
}
private void BuildButton_clicked()
{
string title;
string content;
if (_forceRebuildToggle.value)
{
title = "警告";
content = "确定开始强制构建吗,这样会删除所有已有构建的文件";
}
else
{
title = "提示";
content = "确定开始增量构建吗";
}
if (EditorUtility.DisplayDialog(title, content, "Yes", "No"))
var buildMode = AssetBundleBuilderSettingData.Setting.BuildMode;
if (EditorUtility.DisplayDialog("提示", $"通过构建模式【{buildMode}】来构建!", "Yes", "No"))
{
EditorTools.ClearUnityConsole();
EditorApplication.delayCall += ExecuteBuild;
@@ -178,34 +165,46 @@ namespace YooAsset.Editor
/// </summary>
private void ExecuteBuild()
{
var buildMode = (EBuildMode)_buildModeField.value;
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters();
buildParameters.VerifyBuildingResult = true;
buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = _buildTarget;
buildParameters.BuildMode = buildMode;
buildParameters.BuildVersion = _buildVersionField.value;
buildParameters.CompressOption = (ECompressOption)_compressionField.value;
buildParameters.BuildinTags = _buildinTagsField.value;
buildParameters.VerifyBuildingResult = true;
buildParameters.EnableAddressable = AssetBundleCollectorSettingData.Setting.EnableAddressable;
buildParameters.AppendFileExtension = _appendExtensionToggle.value;
buildParameters.CopyBuildinTagFiles = buildMode == EBuildMode.ForceRebuild;
buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.ForceRebuild = _forceRebuildToggle.value;
buildParameters.BuildinTags = _buildTagsTxt.value;
buildParameters.CompressOption = (ECompressOption)_compressionField.value;
AssetBundleBuilder builder = new AssetBundleBuilder();
builder.Run(buildParameters);
bool succeed = builder.Run(buildParameters);
if (succeed)
{
EditorUtility.RevealInFinder($"{buildParameters.OutputRoot}/{buildParameters.BuildTarget}/{buildParameters.BuildVersion}");
}
}
/// <summary>
/// 获取加密类的类型列表
/// </summary>
// 加密类相关
private int GetEncryptionDefaultIndex(string className)
{
for (int index = 0; index < _encryptionServicesClassNames.Count; index++)
{
if (_encryptionServicesClassNames[index] == className)
{
return index;
}
}
return 0;
}
private List<Type> GetEncryptionServicesClassTypes()
{
List<Type> classTypes = AssemblyUtility.GetAssignableTypes(AssemblyUtility.UnityDefaultAssemblyEditorName, typeof(IEncryptionServices));
return classTypes;
return EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
}
/// <summary>
/// 创建加密类的实例
/// </summary>
private IEncryptionServices CreateEncryptionServicesInstance()
{
if (_encryptionField.index < 0)

View File

@@ -3,10 +3,10 @@
<ui:VisualElement name="BuildContainer">
<ui:TextField picking-mode="Ignore" label="Build Output" name="BuildOutput" />
<uie:IntegerField label="Build Version" value="0" name="BuildVersion" />
<uie:EnumField label="Compression" value="Center" name="Compression" />
<uie:EnumField label="Build Mode" name="BuildMode" />
<ui:VisualElement name="EncryptionContainer" style="height: 24px;" />
<uie:EnumField label="Compression" value="Center" name="Compression" />
<ui:Toggle label="Append Extension" name="AppendExtension" style="height: 15px;" />
<ui:Toggle label="Force Rebuild" name="ForceRebuild" />
<ui:TextField picking-mode="Ignore" label="Buildin Tags" name="BuildinTags" />
<ui:Button text="构建" display-tooltip-when-elided="true" name="Build" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" />
</ui:VisualElement>

View File

@@ -0,0 +1,43 @@
using UnityEditor;
namespace YooAsset.Editor
{
public static class AssetBundleSimulateBuilder
{
private static string _manifestFilePath = string.Empty;
/// <summary>
/// 模拟构建
/// </summary>
public static void SimulateBuild()
{
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters();
buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget;
buildParameters.BuildMode = EBuildMode.SimulateBuild;
buildParameters.BuildVersion = 999;
buildParameters.EnableAddressable = AssetBundleCollectorSettingData.Setting.EnableAddressable;
AssetBundleBuilder builder = new AssetBundleBuilder();
bool buildResult = builder.Run(buildParameters);
if (buildResult)
{
string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(buildParameters.OutputRoot, buildParameters.BuildTarget);
_manifestFilePath = $"{pipelineOutputDirectory}_{EBuildMode.SimulateBuild}/{YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildVersion)}";
}
else
{
_manifestFilePath = null;
}
}
/// <summary>
/// 获取构建的补丁清单路径
/// </summary>
public static string GetPatchManifestPath()
{
return _manifestFilePath;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f94918fa1ea63c34fa0e49fdad4119cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,15 +1,26 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace YooAsset.Editor
{
public class BuildAssetInfo
{
private string _mainBundleName;
private string _shareBundleName;
private bool _isAddAssetTags = false;
private readonly HashSet<string> _referenceBundleNames = new HashSet<string>();
/// <summary>
/// 资源包名称
/// 收集器类型
/// </summary>
public string BundleName { private set; get; }
public ECollectorType CollectorType { private set; get; }
/// <summary>
/// 可寻址地址
/// </summary>
public string Address { private set; get; }
/// <summary>
/// 资源路径
@@ -22,25 +33,20 @@ namespace YooAsset.Editor
public bool IsRawAsset { private set; get; }
/// <summary>
/// 不写入资源列表
/// 是否为着色器资源
/// </summary>
public bool NotWriteToAssetList { private set; get; }
public bool IsShaderAsset { private set; get; }
/// <summary>
/// 是否为主动收集资源
/// </summary>
public bool IsCollectAsset { private set; get; }
/// <summary>
/// 被依赖次数
/// </summary>
public int DependCount = 0;
/// <summary>
/// 资源分类标签列表
/// 资源的分类标签
/// </summary>
public readonly List<string> AssetTags = new List<string>();
/// <summary>
/// 资源包的分类标签
/// </summary>
public readonly List<string> BundleTags = new List<string>();
/// <summary>
/// 依赖的所有资源
/// 注意:包括零依赖资源和冗余资源(资源包名无效)
@@ -48,21 +54,35 @@ namespace YooAsset.Editor
public List<BuildAssetInfo> AllDependAssetInfos { private set; get; }
public BuildAssetInfo(string assetPath, bool isRawAsset, bool notWriteToAssetList)
public BuildAssetInfo(ECollectorType collectorType, string mainBundleName, string address, string assetPath, bool isRawAsset)
{
_mainBundleName = mainBundleName;
CollectorType = collectorType;
Address = address;
AssetPath = assetPath;
IsRawAsset = isRawAsset;
NotWriteToAssetList = notWriteToAssetList;
IsCollectAsset = true;
System.Type assetType = UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
IsShaderAsset = true;
else
IsShaderAsset = false;
}
public BuildAssetInfo(string assetPath)
{
CollectorType = ECollectorType.None;
Address = string.Empty;
AssetPath = assetPath;
IsRawAsset = false;
NotWriteToAssetList = true;
IsCollectAsset = false;
System.Type assetType = UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
IsShaderAsset = true;
else
IsShaderAsset = false;
}
/// <summary>
/// 设置所有依赖的资源
/// </summary>
@@ -75,47 +95,115 @@ namespace YooAsset.Editor
}
/// <summary>
/// 设置资源包名称
/// </summary>
public void SetBundleName(string bundleName)
{
if (string.IsNullOrEmpty(BundleName) == false)
throw new System.Exception("Should never get here !");
BundleName = bundleName;
}
/// <summary>
/// 添加资源分类标签
/// 添加资源的分类标签
/// 说明:原始定义的资源分类标签
/// </summary>
public void AddAssetTags(List<string> tags)
{
if (_isAddAssetTags)
throw new Exception("Should never get here !");
_isAddAssetTags = true;
foreach (var tag in tags)
{
AddAssetTag(tag);
if (AssetTags.Contains(tag) == false)
{
AssetTags.Add(tag);
}
}
}
/// <summary>
/// 添加资源分类标签
/// 添加资源包的分类标签
/// 说明:传染算法统计到的分类标签
/// </summary>
public void AddAssetTag(string tag)
public void AddBundleTags(List<string> tags)
{
if (AssetTags.Contains(tag) == false)
foreach (var tag in tags)
{
AssetTags.Add(tag);
if (BundleTags.Contains(tag) == false)
{
BundleTags.Add(tag);
}
}
}
/// <summary>
/// 资源包名是否有效
/// 资源包名是否存在
/// </summary>
public bool BundleNameIsValid()
public bool HasBundleName()
{
if (string.IsNullOrEmpty(BundleName))
string bundleName = GetBundleName();
if (string.IsNullOrEmpty(bundleName))
return false;
else
return true;
}
/// <summary>
/// 获取资源包名称
/// </summary>
public string GetBundleName()
{
if (CollectorType == ECollectorType.None)
return _shareBundleName;
else
return _mainBundleName;
}
/// <summary>
/// 添加关联的资源包名称
/// </summary>
public void AddReferenceBundleName(string bundleName)
{
if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !");
if (_referenceBundleNames.Contains(bundleName) == false)
_referenceBundleNames.Add(bundleName);
}
/// <summary>
/// 计算主资源或共享资源的完整包名
/// </summary>
public void CalculateFullBundleName()
{
if (CollectorType == ECollectorType.None)
{
if (IsRawAsset)
throw new Exception("Should never get here !");
if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{
if (IsShaderAsset)
{
string shareBundleName = $"{AssetBundleCollectorSettingData.Setting.ShadersBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower();
return;
}
}
if (_referenceBundleNames.Count > 1)
{
IPackRule packRule = PackDirectory.StaticPackRule;
var bundleName = packRule.GetBundleName(new PackRuleData(AssetPath));
var shareBundleName = $"share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower();
}
}
else
{
if (IsRawAsset)
{
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.RawFileVariant}";
_mainBundleName = EditorTools.GetRegularPath(mainBundleName).ToLower();
}
else
{
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_mainBundleName = EditorTools.GetRegularPath(mainBundleName).ToLower(); ;
}
}
}
}
}

View File

@@ -68,14 +68,14 @@ namespace YooAsset.Editor
}
/// <summary>
/// 获取资源标签列表
/// 获取资源包的分类标签列表
/// </summary>
public string[] GetAssetTags()
public string[] GetBundleTags()
{
List<string> result = new List<string>(BuildinAssets.Count);
foreach (var assetInfo in BuildinAssets)
{
foreach (var assetTag in assetInfo.AssetTags)
foreach (var assetTag in assetInfo.BundleTags)
{
if (result.Contains(assetTag) == false)
result.Add(assetTag);
@@ -105,7 +105,7 @@ namespace YooAsset.Editor
/// </summary>
public BuildAssetInfo[] GetAllPatchAssetInfos()
{
return BuildinAssets.Where(t => t.IsCollectAsset && t.NotWriteToAssetList == false).ToArray();
return BuildinAssets.Where(t => t.CollectorType == ECollectorType.MainAssetCollector).ToArray();
}
/// <summary>

View File

@@ -25,13 +25,17 @@ namespace YooAsset.Editor
/// </summary>
public void PackAsset(BuildAssetInfo assetInfo)
{
if (TryGetBundleInfo(assetInfo.BundleName, out BuildBundleInfo bundleInfo))
string bundleName = assetInfo.GetBundleName();
if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !");
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{
bundleInfo.PackAsset(assetInfo);
}
else
{
BuildBundleInfo newBundleInfo = new BuildBundleInfo(assetInfo.BundleName);
BuildBundleInfo newBundleInfo = new BuildBundleInfo(bundleName);
newBundleInfo.PackAsset(assetInfo);
BundleInfos.Add(newBundleInfo);
}
@@ -51,13 +55,13 @@ namespace YooAsset.Editor
}
/// <summary>
/// 获取AssetBundle内包含的标记列表
/// 获取资源包的分类标签列表
/// </summary>
public string[] GetAssetTags(string bundleName)
public string[] GetBundleTags(string bundleName)
{
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{
return bundleInfo.GetAssetTags();
return bundleInfo.GetBundleTags();
}
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}");
}

View File

@@ -0,0 +1,136 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
public static class BuildMapCreater
{
/// <summary>
/// 执行资源构建上下文
/// </summary>
public static BuildMapContext CreateBuildMap(EBuildMode buildMode)
{
BuildMapContext context = new BuildMapContext();
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
AssetBundleCollectorSettingData.Setting.CheckConfigError();
// 2. 获取所有收集器收集的资源
List<CollectAssetInfo> allCollectAssets = AssetBundleCollectorSettingData.Setting.GetAllCollectAssets(buildMode);
// 3. 剔除未被引用的依赖资源
List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>();
foreach (var collectAssetInfo in allCollectAssets)
{
if (collectAssetInfo.CollectorType == ECollectorType.DependAssetCollector)
{
if (IsRemoveDependAsset(allCollectAssets, collectAssetInfo.AssetPath))
removeDependList.Add(collectAssetInfo);
}
}
foreach (var removeValue in removeDependList)
{
allCollectAssets.Remove(removeValue);
}
// 4. 录入所有收集器收集的资源
foreach (var collectAssetInfo in allCollectAssets)
{
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 5. 录入相关依赖的资源
foreach (var collectAssetInfo in allCollectAssets)
{
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.ContainsKey(dependAssetPath))
{
buildAssetDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetInfo.BundleName);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetInfo.BundleName);
buildAssetDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
context.AssetFileCount = buildAssetDic.Count;
// 6. 填充主动收集资源的依赖列表
foreach (var collectAssetInfo in allCollectAssets)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
buildAssetDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 7. 计算完整的资源包名
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
pair.Value.CalculateFullBundleName();
}
// 8. 移除不参与构建的资源
List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.HasBundleName() == false)
removeBuildList.Add(buildAssetInfo);
}
foreach (var removeValue in removeBuildList)
{
buildAssetDic.Remove(removeValue.AssetPath);
}
// 9. 构建资源包
var allBuildinAssets = buildAssetDic.Values.ToList();
if (allBuildinAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allBuildinAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
private static bool IsRemoveDependAsset(List<CollectAssetInfo> allCollectAssets, string dependAssetPath)
{
foreach (var collectAssetInfo in allCollectAssets)
{
var collectorType = collectAssetInfo.CollectorType;
if (collectorType == ECollectorType.MainAssetCollector || collectorType == ECollectorType.StaticAssetCollector)
{
if (collectAssetInfo.DependAssets.Contains(dependAssetPath))
return false;
}
}
BuildRunner.Log($"发现未被依赖的资源并自动移除 : {dependAssetPath}");
return true;
}
}
}

View File

@@ -1,113 +0,0 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
public static class BuildMapHelper
{
/// <summary>
/// 执行资源构建上下文
/// </summary>
public static BuildMapContext SetupBuildMap()
{
BuildMapContext context = new BuildMapContext();
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>();
// 0. 检测配置合法性
AssetBundleGrouperSettingData.Setting.CheckConfigError();
// 1. 获取主动收集的资源
List<CollectAssetInfo> collectAssetInfos = AssetBundleGrouperSettingData.Setting.GetAllCollectAssets();
// 2. 录入主动收集的资源
foreach (var collectAssetInfo in collectAssetInfos)
{
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset, collectAssetInfo.NotWriteToAssetList);
buildAssetInfo.SetBundleName(collectAssetInfo.BundleName);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
}
else
{
throw new Exception($"Should never get here !");
}
}
// 3. 录入并分析依赖资源
foreach (var collectAssetInfo in collectAssetInfos)
{
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.ContainsKey(dependAssetPath))
{
buildAssetDic[dependAssetPath].DependCount++;
buildAssetDic[dependAssetPath].AddAssetTags(collectAssetInfo.AssetTags);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
context.AssetFileCount = buildAssetDic.Count;
// 4. 设置主动收集资源的依赖列表
foreach (var collectAssetInfo in collectAssetInfos)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.TryGetValue(dependAssetPath, out BuildAssetInfo value))
dependAssetInfos.Add(value);
else
throw new Exception("Should never get here !");
}
buildAssetDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 5. 移除零依赖的资源
List<BuildAssetInfo> removeList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.IsCollectAsset)
continue;
if (buildAssetInfo.DependCount == 0)
removeList.Add(buildAssetInfo);
}
foreach (var removeValue in removeList)
{
buildAssetDic.Remove(removeValue.AssetPath);
}
// 6. 设置未命名的资源包
IPackRule defaultPackRule = new PackDirectory();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
var buildAssetInfo = pair.Value;
if (buildAssetInfo.BundleNameIsValid() == false)
{
string bundleName = defaultPackRule.GetBundleName(new PackRuleData(buildAssetInfo.AssetPath));
bundleName = AssetBundleCollector.RevisedBundleName(bundleName, false);
buildAssetInfo.SetBundleName(bundleName);
}
}
// 7. 构建资源包
var allBuildAssets = buildAssetDic.Values.ToList();
if (allBuildAssets.Count == 0)
throw new Exception("构建的资源列表不能为空");
foreach (var assetInfo in allBuildAssets)
{
context.PackAsset(assetInfo);
}
return context;
}
}
}

View File

@@ -9,11 +9,6 @@ namespace YooAsset.Editor
/// </summary>
public class BuildParameters
{
/// <summary>
/// 验证构建结果
/// </summary>
public bool VerifyBuildingResult = false;
/// <summary>
/// 输出的根目录
/// </summary>
@@ -24,48 +19,53 @@ namespace YooAsset.Editor
/// </summary>
public BuildTarget BuildTarget;
/// <summary>
/// 构建模式
/// </summary>
public EBuildMode BuildMode;
/// <summary>
/// 构建的版本(资源版本号)
/// </summary>
public int BuildVersion;
/// <summary>
/// 启用自动分包机制
/// 说明:自动分包机制可以实现资源零冗余
/// 内置资源标签集合(首包资源标签)
/// 注意:分号为分隔符
/// </summary>
public bool EnableAutoCollect = true;
public string BuildinTags;
/// <summary>
/// 验证构建结果
/// </summary>
public bool VerifyBuildingResult = false;
/// <summary>
/// 启用可寻址资源定位
/// </summary>
public bool EnableAddressable = false;
/// <summary>
/// 追加文件扩展名
/// </summary>
public bool AppendFileExtension = false;
/// <summary>
/// 拷贝内置资源文件到StreamingAssets目录首包资源文件
/// </summary>
public bool CopyBuildinTagFiles = false;
/// <summary>
/// 加密类
/// </summary>
public IEncryptionServices EncryptionServices;
/// <summary>
/// 强制重新构建整个项目如果为FALSE则是增量打包
/// </summary>
public bool ForceRebuild;
/// <summary>
/// 内置资源的标记列表
/// 注意:分号为分隔符
/// </summary>
public string BuildinTags;
public IEncryptionServices EncryptionServices = null;
/// <summary>
/// 压缩选项
/// </summary>
public ECompressOption CompressOption;
/// <summary>
/// 文件名附加上哈希值
/// </summary>
public bool AppendHash = false;
public ECompressOption CompressOption = ECompressOption.Uncompressed;
/// <summary>
/// 禁止写入类型树结构(可以降低包体和内存并提高加载效率)
@@ -77,14 +77,9 @@ namespace YooAsset.Editor
/// </summary>
public bool IgnoreTypeTreeChanges = true;
/// <summary>
/// 禁用名称查找资源(可以降内存并提高加载效率)
/// </summary>
public bool DisableLoadAssetByFileName = false;
/// <summary>
/// 获取内置标记列表
/// 获取内置资源标签列表(首包资源标签)
/// </summary>
public List<string> GetBuildinTags()
{

View File

@@ -0,0 +1,97 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
namespace YooAsset.Editor
{
public class BuildParametersContext : IContextObject
{
private readonly System.Diagnostics.Stopwatch _buildWatch = new System.Diagnostics.Stopwatch();
/// <summary>
/// 构建参数
/// </summary>
public BuildParameters Parameters { private set; get; }
/// <summary>
/// 构建管线的输出目录
/// </summary>
public string PipelineOutputDirectory { private set; get; }
public BuildParametersContext(BuildParameters parameters)
{
Parameters = parameters;
PipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(parameters.OutputRoot, parameters.BuildTarget);
if (parameters.BuildMode == EBuildMode.DryRunBuild)
PipelineOutputDirectory += $"_{EBuildMode.DryRunBuild}";
else if (parameters.BuildMode == EBuildMode.SimulateBuild)
PipelineOutputDirectory += $"_{EBuildMode.SimulateBuild}";
}
/// <summary>
/// 获取本次构建的补丁目录
/// </summary>
public string GetPackageDirectory()
{
return $"{Parameters.OutputRoot}/{Parameters.BuildTarget}/{Parameters.BuildVersion}";
}
/// <summary>
/// 获取构建选项
/// </summary>
public BuildAssetBundleOptions GetPipelineBuildOptions()
{
// For the new build system, unity always need BuildAssetBundleOptions.CollectDependencies and BuildAssetBundleOptions.DeterministicAssetBundle
// 除非设置ForceRebuildAssetBundle标记否则会进行增量打包
BuildAssetBundleOptions opt = BuildAssetBundleOptions.None;
opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it.
if (Parameters.BuildMode == EBuildMode.SimulateBuild)
throw new Exception("Should never get here !");
if (Parameters.BuildMode == EBuildMode.DryRunBuild)
{
opt |= BuildAssetBundleOptions.DryRunBuild;
return opt;
}
if (Parameters.CompressOption == ECompressOption.Uncompressed)
opt |= BuildAssetBundleOptions.UncompressedAssetBundle;
else if (Parameters.CompressOption == ECompressOption.LZ4)
opt |= BuildAssetBundleOptions.ChunkBasedCompression;
if (Parameters.BuildMode == EBuildMode.ForceRebuild)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (Parameters.DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (Parameters.IgnoreTypeTreeChanges)
opt |= BuildAssetBundleOptions.IgnoreTypeTreeChanges; //Ignore the type tree changes when doing the incremental build check.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileName; //Disables Asset Bundle LoadAsset by file name.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
return opt;
}
/// <summary>
/// 获取构建的耗时(单位:秒)
/// </summary>
public float GetBuildingSeconds()
{
float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return seconds;
}
public void BeginWatch()
{
_buildWatch.Start();
}
public void StopWatch()
{
_buildWatch.Stop();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b84510feab7cbe44a9b6d8ef0b3f559c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -7,15 +7,36 @@ namespace YooAsset.Editor
[Serializable]
public class ReportAssetInfo
{
/// <summary>
/// 可寻址地址
/// </summary>
public string Address;
/// <summary>
/// 资源路径
/// </summary>
public string AssetPath;
/// <summary>
/// 资源GUID
/// 说明Meta文件记录的GUID
/// </summary>
public string AssetGUID;
/// <summary>
/// 资源的分类标签
/// </summary>
public string[] AssetTags;
/// <summary>
/// 所属资源包名称
/// </summary>
public string MainBundle;
public string MainBundleName;
/// <summary>
/// 所属资源包的大小
/// </summary>
public long MainBundleSize;
/// <summary>
/// 依赖的资源包名称列表

View File

@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
@@ -7,6 +8,21 @@ namespace YooAsset.Editor
[Serializable]
public class ReportBundleInfo
{
public class FlagsData
{
public bool IsEncrypted { private set; get; }
public bool IsBuildin { private set; get; }
public bool IsRawFile { private set; get; }
public FlagsData(bool isEncrypted, bool isBuildin, bool isRawFile)
{
IsEncrypted = isEncrypted;
IsBuildin = isBuildin;
IsRawFile = isRawFile;
}
}
private FlagsData _flagData;
/// <summary>
/// 资源包名称
/// </summary>
@@ -36,5 +52,44 @@ namespace YooAsset.Editor
/// Flags
/// </summary>
public int Flags;
/// <summary>
/// 获取标志位的解析数据
/// </summary>
public FlagsData GetFlagData()
{
if (_flagData == null)
{
BitMask32 value = Flags;
bool isEncrypted = value.Test(0);
bool isBuildin = value.Test(1);
bool isRawFile = value.Test(2);
_flagData = new FlagsData(isEncrypted, isBuildin, isRawFile);
}
return _flagData;
}
/// <summary>
/// 获取资源分类标签的字符串
/// </summary>
public string GetTagsString()
{
if (Tags != null)
return String.Join(";", Tags);
else
return string.Empty;
}
/// <summary>
/// 是否为原生文件
/// </summary>
public bool IsRawFile()
{
if (System.IO.Path.GetExtension(BundleName) == $".{YooAssetSettingsData.Setting.RawFileVariant}")
return true;
else
return false;
}
}
}

View File

@@ -28,21 +28,36 @@ namespace YooAsset.Editor
/// </summary>
public BuildTarget BuildTarget;
/// <summary>
/// 构建模式
/// </summary>
public EBuildMode BuildMode;
/// <summary>
/// 构建版本
/// </summary>
public int BuildVersion;
/// <summary>
/// 启用自动分包机制
/// 内置资源标签
/// </summary>
public bool EnableAutoCollect;
public string BuildinTags;
/// <summary>
/// 启用可寻址资源定位
/// </summary>
public bool EnableAddressable;
/// <summary>
/// 追加文件扩展名
/// </summary>
public bool AppendFileExtension;
/// <summary>
/// 拷贝内置资源文件
/// </summary>
public bool CopyBuildinTagFiles;
/// <summary>
/// 自动收集着色器
/// </summary>
@@ -59,13 +74,9 @@ namespace YooAsset.Editor
public string EncryptionServicesClassName;
// 构建参数
public bool ForceRebuild;
public string BuildinTags;
public ECompressOption CompressOption;
public bool AppendHash;
public bool DisableWriteTypeTree;
public bool IgnoreTypeTreeChanges;
public bool DisableLoadAssetByFileName;
// 构建结果
public int AssetFileTotalCount;

View File

@@ -1,12 +1,15 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
namespace YooAsset.Editor
{
public class BuildRunner
{
public static bool EnableLog = true;
/// <summary>
/// 执行构建流程
/// </summary>
@@ -24,11 +27,14 @@ namespace YooAsset.Editor
IBuildTask task = pipeline[i];
try
{
var taskAttribute = task.GetType().GetCustomAttribute<TaskAttribute>();
Log($"---------------------------------------->{taskAttribute.Desc}");
task.Run(context);
}
catch (Exception e)
{
Debug.LogError($"Build task {task.GetType().Name} failed : {e}");
Debug.LogError($"Build task {task.GetType().Name} failed !");
Debug.LogError($"Build error : {e}");
succeed = false;
break;
}
@@ -37,5 +43,24 @@ namespace YooAsset.Editor
// 返回运行结果
return succeed;
}
/// <summary>
/// 日志输出
/// </summary>
public static void Log(string info)
{
if (EnableLog)
{
UnityEngine.Debug.Log(info);
}
}
/// <summary>
/// 日志输出
/// </summary>
public static void Info(string info)
{
UnityEngine.Debug.Log(info);
}
}
}

View File

@@ -0,0 +1,14 @@
using System;
namespace YooAsset.Editor
{
[AttributeUsage(AttributeTargets.Class)]
public class TaskAttribute : Attribute
{
public string Desc;
public TaskAttribute(string desc)
{
Desc = desc;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 35749e57d9a3da84aa60c348bc6bbe9d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -8,6 +8,7 @@ using UnityEngine;
namespace YooAsset.Editor
{
[TaskAttribute("资源构建内容打包")]
public class TaskBuilding : IBuildTask
{
public class UnityManifestContext : IContextObject
@@ -17,178 +18,48 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
Debug.Log($"开始构建......");
// 模拟构建模式下跳过引擎构建
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.SimulateBuild)
return;
BuildAssetBundleOptions opt = buildParametersContext.GetPipelineBuildOptions();
AssetBundleManifest unityManifest = BuildPipeline.BuildAssetBundles(buildParametersContext.PipelineOutputDirectory, buildMapContext.GetPipelineBuilds(), opt, buildParametersContext.Parameters.BuildTarget);
if (unityManifest == null)
throw new Exception("构建过程中发生错误!");
BuildRunner.Log("Unity引擎打包成功");
UnityManifestContext unityManifestContext = new UnityManifestContext();
unityManifestContext.UnityManifest = unityManifest;
context.SetContextObject(unityManifestContext);
// 拷贝原生文件
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyRawBundle(buildMapContext, buildParametersContext);
}
}
/// <summary>
/// 拷贝原生文件
/// </summary>
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string dest = $"{buildParametersContext.PipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach(var buildAsset in bundleInfo.BuildinAssets)
foreach (var buildAsset in bundleInfo.BuildinAssets)
{
if(buildAsset.IsRawAsset)
if (buildAsset.IsRawAsset)
EditorTools.CopyFile(buildAsset.AssetPath, dest, true);
}
}
}
// 验证构建结果
if (buildParametersContext.Parameters.VerifyBuildingResult)
{
VerifyingBuildingResult(context, unityManifest);
}
}
/// <summary>
/// 验证构建结果
/// </summary>
private void VerifyingBuildingResult(BuildContext context, AssetBundleManifest unityManifest)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
string[] buildedBundles = unityManifest.GetAllAssetBundles();
// 1. 过滤掉原生Bundle
List<BuildBundleInfo> expectBundles = new List<BuildBundleInfo>(buildedBundles.Length);
foreach(var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile == false)
expectBundles.Add(bundleInfo);
}
// 2. 验证数量
if (buildedBundles.Length != expectBundles.Count)
{
Debug.LogWarning($"构建过程中可能存在无效的资源导致和预期构建的Bundle数量不一致");
}
// 3. 正向验证Bundle
foreach (var bundleName in buildedBundles)
{
if (buildMapContext.IsContainsBundle(bundleName) == false)
{
throw new Exception($"Should never get here !");
}
}
// 4. 反向验证Bundle
bool isPass = true;
foreach (var expectBundle in expectBundles)
{
bool isMatch = false;
foreach (var buildedBundle in buildedBundles)
{
if (buildedBundle == expectBundle.BundleName)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
isPass = false;
Debug.LogWarning($"没有找到预期构建的Bundle文件 : {expectBundle.BundleName}");
}
}
if(isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
// 5. 验证Asset
int progressValue = 0;
foreach (var buildedBundle in buildedBundles)
{
string filePath = $"{buildParameters.PipelineOutputDirectory}/{buildedBundle}";
string[] allBuildinAssetPaths = GetAssetBundleAllAssets(filePath);
string[] expectBuildinAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
if (expectBuildinAssetPaths.Length != allBuildinAssetPaths.Length)
{
Debug.LogWarning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
isPass = false;
continue;
}
foreach (var buildinAssetPath in allBuildinAssetPaths)
{
var guid = AssetDatabase.AssetPathToGUID(buildinAssetPath);
if (string.IsNullOrEmpty(guid))
{
Debug.LogWarning($"无效的资源路径,请检查路径是否带有特殊符号或中文:{buildinAssetPath}");
isPass = false;
continue;
}
bool isMatch = false;
foreach (var exceptBuildAssetPath in expectBuildinAssetPaths)
{
var guidExcept = AssetDatabase.AssetPathToGUID(exceptBuildAssetPath);
if (guid == guidExcept)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
Debug.LogWarning($"在构建的Bundle文件里发现了没有匹配的资源对象{buildinAssetPath}");
isPass = false;
continue;
}
}
EditorTools.DisplayProgressBar("验证构建结果", ++progressValue, buildedBundles.Length);
}
EditorTools.ClearProgressBar();
if (isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
// 卸载所有加载的Bundle
Debug.Log("构建结果验证成功!");
}
/// <summary>
/// 解析.manifest文件并获取资源列表
/// </summary>
private string[] GetAssetBundleAllAssets(string filePath)
{
string manifestFilePath = $"{filePath}.manifest";
List<string> assetLines = new List<string>();
using (StreamReader reader = File.OpenText(manifestFilePath))
{
string content;
bool findTarget = false;
while (null != (content = reader.ReadLine()))
{
if (content.StartsWith("Dependencies:"))
break;
if (findTarget == false && content.StartsWith("Assets:"))
findTarget = true;
if (findTarget)
{
if (content.StartsWith("- "))
{
string assetPath = content.TrimStart("- ".ToCharArray());
assetLines.Add(assetPath);
}
}
}
}
return assetLines.ToArray();
}
}
}

View File

@@ -6,16 +6,14 @@ using UnityEngine;
namespace YooAsset.Editor
{
/// <summary>
/// 拷贝内置文件到StreamingAssets
/// </summary>
[TaskAttribute("拷贝内置文件到流目录")]
public class TaskCopyBuildinFiles : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
// 注意:我们只有在强制重建的时候才会拷贝
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
if (buildParameters.Parameters.ForceRebuild)
var buildParameters = context.GetContextObject<BuildParametersContext>();
if (buildParameters.Parameters.CopyBuildinTagFiles)
{
// 清空流目录
AssetBundleBuilderHelper.ClearStreamingAssetsFolder();
@@ -38,7 +36,6 @@ namespace YooAsset.Editor
string sourcePath = $"{pipelineOutputDirectory}/{patchBundle.BundleName}";
string destPath = $"{AssetBundleBuilderHelper.GetStreamingAssetsFolderPath()}/{patchBundle.Hash}";
Debug.Log($"拷贝内置文件到流目录:{patchBundle.BundleName}");
EditorTools.CopyFile(sourcePath, destPath, true);
}
@@ -65,6 +62,7 @@ namespace YooAsset.Editor
// 刷新目录
AssetDatabase.Refresh();
BuildRunner.Log($"内置文件拷贝完成:{AssetBundleBuilderHelper.GetStreamingAssetsFolderPath()}");
}
}
}

View File

@@ -5,72 +5,70 @@ using System.Collections.Generic;
namespace YooAsset.Editor
{
/// <summary>
/// 创建补丁清单文件
/// </summary>
[TaskAttribute("创建补丁清单文件")]
public class TaskCreatePatchManifest : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var encryptionContext = context.GetContextObject<TaskEncryption.EncryptionContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var encryptionContext = context.GetContextObject<TaskEncryption.EncryptionContext>();
CreatePatchManifestFile(buildParameters, buildMapContext, encryptionContext);
}
/// <summary>
/// 创建补丁清单文件到输出目录
/// </summary>
private void CreatePatchManifestFile(AssetBundleBuilder.BuildParametersContext buildParameters,
BuildMapContext buildMapContext, TaskEncryption.EncryptionContext encryptionContext)
private void CreatePatchManifestFile(BuildParametersContext buildParameters, BuildMapContext buildMapContext,
TaskEncryption.EncryptionContext encryptionContext)
{
int resourceVersion = buildParameters.Parameters.BuildVersion;
// 创建新补丁清单
PatchManifest patchManifest = new PatchManifest();
patchManifest.EnableAddressable = buildParameters.Parameters.EnableAddressable;
patchManifest.ResourceVersion = buildParameters.Parameters.BuildVersion;
patchManifest.BuildinTags = buildParameters.Parameters.BuildinTags;
patchManifest.BundleList = GetAllPatchBundle(buildParameters, buildMapContext, encryptionContext);
patchManifest.AssetList = GetAllPatchAsset(buildMapContext, patchManifest);
patchManifest.AssetList = GetAllPatchAsset(buildParameters, buildMapContext, patchManifest);
// 创建补丁清单文件
string manifestFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestFileName(resourceVersion)}";
UnityEngine.Debug.Log($"创建补丁清单文件:{manifestFilePath}");
BuildRunner.Log($"创建补丁清单文件:{manifestFilePath}");
PatchManifest.Serialize(manifestFilePath, patchManifest);
// 创建补丁清单哈希文件
string manifestHashFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestHashFileName(resourceVersion)}";
string manifestHash = HashUtility.FileMD5(manifestFilePath);
UnityEngine.Debug.Log($"创建补丁清单哈希文件:{manifestHashFilePath}");
BuildRunner.Log($"创建补丁清单哈希文件:{manifestHashFilePath}");
FileUtility.CreateFile(manifestHashFilePath, manifestHash);
// 创建静态版本文件
string staticVersionFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.VersionFileName}";
string staticVersion = resourceVersion.ToString();
UnityEngine.Debug.Log($"创建静态版本文件:{staticVersionFilePath}");
BuildRunner.Log($"创建静态版本文件:{staticVersionFilePath}");
FileUtility.CreateFile(staticVersionFilePath, staticVersion);
}
/// <summary>
/// 获取资源包列表
/// </summary>
private List<PatchBundle> GetAllPatchBundle(AssetBundleBuilder.BuildParametersContext buildParameters,
BuildMapContext buildMapContext, TaskEncryption.EncryptionContext encryptionContext)
private List<PatchBundle> GetAllPatchBundle(BuildParametersContext buildParameters, BuildMapContext buildMapContext,
TaskEncryption.EncryptionContext encryptionContext)
{
List<PatchBundle> result = new List<PatchBundle>(1000);
// 内置标记列表
List<string> buildinTags = buildParameters.Parameters.GetBuildinTags();
var buildMode = buildParameters.Parameters.BuildMode;
bool standardBuild = buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild;
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
var bundleName = bundleInfo.BundleName;
string filePath = $"{buildParameters.PipelineOutputDirectory}/{bundleName}";
string hash = HashUtility.FileMD5(filePath);
string crc32 = HashUtility.FileCRC32(filePath);
long size = FileUtility.GetFileSize(filePath);
int version = buildParameters.Parameters.BuildVersion;
string[] tags = buildMapContext.GetAssetTags(bundleName);
string hash = GetFileHash(filePath, standardBuild);
string crc32 = GetFileCRC(filePath, standardBuild);
long size = GetFileSize(filePath, standardBuild);
string[] tags = buildMapContext.GetBundleTags(bundleName);
bool isEncrypted = encryptionContext.IsEncryptFile(bundleName);
bool isBuildin = IsBuildinBundle(tags, buildinTags);
bool isRawFile = bundleInfo.IsRawFile;
@@ -90,7 +88,7 @@ namespace YooAsset.Editor
}
private bool IsBuildinBundle(string[] bundleTags, List<string> buildinTags)
{
// 注意:没有任何标记的Bundle文件默认为内置文件
// 注意:没有任何分类标签的Bundle文件默认为内置文件
if (bundleTags.Length == 0)
return true;
@@ -101,11 +99,32 @@ namespace YooAsset.Editor
}
return false;
}
private string GetFileHash(string filePath, bool standardBuild)
{
if (standardBuild)
return HashUtility.FileMD5(filePath);
else
return "00000000000000000000000000000000"; //32位
}
private string GetFileCRC(string filePath, bool standardBuild)
{
if (standardBuild)
return HashUtility.FileCRC32(filePath);
else
return "00000000"; //8位
}
private long GetFileSize(string filePath, bool standardBuild)
{
if (standardBuild)
return FileUtility.GetFileSize(filePath);
else
return 0;
}
/// <summary>
/// 获取资源列表
/// </summary>
private List<PatchAsset> GetAllPatchAsset(BuildMapContext buildMapContext, PatchManifest patchManifest)
private List<PatchAsset> GetAllPatchAsset(BuildParametersContext buildParameters, BuildMapContext buildMapContext, PatchManifest patchManifest)
{
List<PatchAsset> result = new List<PatchAsset>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos)
@@ -114,8 +133,13 @@ namespace YooAsset.Editor
foreach (var assetInfo in assetInfos)
{
PatchAsset patchAsset = new PatchAsset();
if (buildParameters.Parameters.EnableAddressable)
patchAsset.Address = assetInfo.Address;
else
patchAsset.Address = string.Empty;
patchAsset.AssetPath = assetInfo.AssetPath;
patchAsset.BundleID = GetAssetBundleID(assetInfo.BundleName, patchManifest);
patchAsset.AssetTags = assetInfo.AssetTags.ToArray();
patchAsset.BundleID = GetAssetBundleID(assetInfo.GetBundleName(), patchManifest);
patchAsset.DependIDs = GetAssetBundleDependIDs(patchAsset.BundleID, assetInfo, patchManifest);
result.Add(patchAsset);
}
@@ -127,13 +151,14 @@ namespace YooAsset.Editor
List<int> result = new List<int>();
foreach (var dependAssetInfo in assetInfo.AllDependAssetInfos)
{
if (dependAssetInfo.BundleNameIsValid() == false)
continue;
int bundleID = GetAssetBundleID(dependAssetInfo.BundleName, patchManifest);
if (mainBundleID != bundleID)
if (dependAssetInfo.HasBundleName())
{
if (result.Contains(bundleID) == false)
result.Add(bundleID);
int bundleID = GetAssetBundleID(dependAssetInfo.GetBundleName(), patchManifest);
if (mainBundleID != bundleID)
{
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
}
}
return result.ToArray();

View File

@@ -3,32 +3,34 @@ using System.Collections.Generic;
namespace YooAsset.Editor
{
/// <summary>
/// 制作补丁包
/// </summary>
[TaskAttribute("制作补丁包")]
public class TaskCreatePatchPackage : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
CopyPatchFiles(buildParameters);
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyPatchFiles(buildParameters);
}
}
/// <summary>
/// 拷贝补丁文件到补丁包目录
/// </summary>
private void CopyPatchFiles(AssetBundleBuilder.BuildParametersContext buildParameters)
private void CopyPatchFiles(BuildParametersContext buildParameters)
{
int resourceVersion = buildParameters.Parameters.BuildVersion;
string packageDirectory = buildParameters.GetPackageDirectory();
UnityEngine.Debug.Log($"准备开始拷贝补丁文件到补丁包目录:{packageDirectory}");
BuildRunner.Log($"开始拷贝补丁文件到补丁包目录:{packageDirectory}");
// 拷贝Report文件
{
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.ReportFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettings.ReportFileName}";
string reportFileName = YooAssetSettingsData.GetReportFileName(buildParameters.Parameters.BuildVersion);
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{reportFileName}";
string destPath = $"{packageDirectory}/{reportFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝构建报告文件到:{destPath}");
}
// 拷贝补丁清单文件
@@ -36,7 +38,6 @@ namespace YooAsset.Editor
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestFileName(resourceVersion)}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.GetPatchManifestFileName(resourceVersion)}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝补丁清单文件到:{destPath}");
}
// 拷贝补丁清单哈希文件
@@ -44,7 +45,6 @@ namespace YooAsset.Editor
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestHashFileName(resourceVersion)}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.GetPatchManifestHashFileName(resourceVersion)}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝补丁清单哈希文件到:{destPath}");
}
// 拷贝静态版本文件
@@ -52,7 +52,6 @@ namespace YooAsset.Editor
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.VersionFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettings.VersionFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝静态版本文件到:{destPath}");
}
// 拷贝UnityManifest序列化文件
@@ -60,7 +59,6 @@ namespace YooAsset.Editor
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}";
string destPath = $"{packageDirectory}/{YooAssetSettingsData.Setting.UnityManifestFileName}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝UnityManifest文件到{destPath}");
}
// 拷贝UnityManifest文本文件
@@ -79,7 +77,6 @@ namespace YooAsset.Editor
string sourcePath = $"{buildParameters.PipelineOutputDirectory}/{patchBundle.BundleName}";
string destPath = $"{packageDirectory}/{patchBundle.Hash}";
EditorTools.CopyFile(sourcePath, destPath, true);
UnityEngine.Debug.Log($"拷贝补丁文件到补丁包:{patchBundle.BundleName}");
EditorTools.DisplayProgressBar("拷贝补丁文件", ++progressValue, patchFileTotalCount);
}
EditorTools.ClearProgressBar();

View File

@@ -1,49 +1,57 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
namespace YooAsset.Editor
{
/// <summary>
/// 创建报告文件
/// </summary>
[TaskAttribute("创建构建报告文件")]
public class TaskCreateReport : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
CreateReportFile(buildParameters, buildMapContext);
buildParameters.StopWatch();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild)
{
CreateReportFile(buildParameters, buildMapContext);
}
else
{
float buildSeconds = buildParameters.GetBuildingSeconds();
BuildRunner.Info($"Build time consuming {buildSeconds} seconds.");
}
}
private void CreateReportFile(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
private void CreateReportFile(BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory, buildParameters.Parameters.BuildVersion);
BuildReport buildReport = new BuildReport();
buildParameters.StopWatch();
BuildReport buildReport = new BuildReport();
// 概述信息
{
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildTime = DateTime.Now.ToString();
buildReport.Summary.BuildSeconds = buildParameters.GetBuildingSeconds();
buildReport.Summary.BuildSeconds = (int)buildParameters.GetBuildingSeconds();
buildReport.Summary.BuildTarget = buildParameters.Parameters.BuildTarget;
buildReport.Summary.BuildMode = buildParameters.Parameters.BuildMode;
buildReport.Summary.BuildVersion = buildParameters.Parameters.BuildVersion;
buildReport.Summary.EnableAutoCollect = buildParameters.Parameters.EnableAutoCollect;
buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags;
buildReport.Summary.EnableAddressable = buildParameters.Parameters.EnableAddressable;
buildReport.Summary.AppendFileExtension = buildParameters.Parameters.AppendFileExtension;
buildReport.Summary.AutoCollectShaders = AssetBundleGrouperSettingData.Setting.AutoCollectShaders;
buildReport.Summary.ShadersBundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName;
buildReport.Summary.CopyBuildinTagFiles = buildParameters.Parameters.CopyBuildinTagFiles;
buildReport.Summary.AutoCollectShaders = AssetBundleCollectorSettingData.Setting.AutoCollectShaders;
buildReport.Summary.ShadersBundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.Parameters.EncryptionServices == null ?
"null" : buildParameters.Parameters.EncryptionServices.GetType().FullName;
// 构建参数
buildReport.Summary.ForceRebuild = buildParameters.Parameters.ForceRebuild;
buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags;
buildReport.Summary.CompressOption = buildParameters.Parameters.CompressOption;
buildReport.Summary.AppendHash = buildParameters.Parameters.AppendHash;
buildReport.Summary.DisableWriteTypeTree = buildParameters.Parameters.DisableWriteTypeTree;
buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.Parameters.IgnoreTypeTreeChanges;
buildReport.Summary.DisableLoadAssetByFileName = buildParameters.Parameters.DisableLoadAssetByFileName;
// 构建结果
buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount;
@@ -63,8 +71,12 @@ namespace YooAsset.Editor
{
var mainBundle = patchManifest.BundleList[patchAsset.BundleID];
ReportAssetInfo reportAssetInfo = new ReportAssetInfo();
reportAssetInfo.Address = patchAsset.Address;
reportAssetInfo.AssetPath = patchAsset.AssetPath;
reportAssetInfo.MainBundle = mainBundle.BundleName;
reportAssetInfo.AssetTags = patchAsset.AssetTags;
reportAssetInfo.AssetGUID = AssetDatabase.AssetPathToGUID(patchAsset.AssetPath);
reportAssetInfo.MainBundleName = mainBundle.BundleName;
reportAssetInfo.MainBundleSize = mainBundle.SizeBytes;
reportAssetInfo.DependBundles = GetDependBundles(patchManifest, patchAsset);
reportAssetInfo.DependAssets = GetDependAssets(buildMapContext, mainBundle.BundleName, patchAsset.AssetPath);
buildReport.AssetInfos.Add(reportAssetInfo);
@@ -85,12 +97,13 @@ namespace YooAsset.Editor
}
// 删除旧文件
string filePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.ReportFileName}";
string filePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetReportFileName(buildParameters.Parameters.BuildVersion)}";
if (File.Exists(filePath))
File.Delete(filePath);
// 序列化文件
BuildReport.Serialize(filePath, buildReport);
BuildRunner.Log($"资源构建报告文件创建完成:{filePath}");
}
/// <summary>

View File

@@ -6,6 +6,7 @@ using System.Collections.Generic;
namespace YooAsset.Editor
{
[TaskAttribute("资源包加密")]
public class TaskEncryption : IBuildTask
{
public class EncryptionContext : IContextObject
@@ -23,18 +24,28 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
EncryptionContext encryptionContext = new EncryptionContext();
encryptionContext.EncryptList = EncryptFiles(buildParameters, buildMapContext);
context.SetContextObject(encryptionContext);
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
EncryptionContext encryptionContext = new EncryptionContext();
encryptionContext.EncryptList = EncryptFiles(buildParameters, buildMapContext);
context.SetContextObject(encryptionContext);
}
else
{
EncryptionContext encryptionContext = new EncryptionContext();
encryptionContext.EncryptList = new List<string>();
context.SetContextObject(encryptionContext);
}
}
/// <summary>
/// 加密文件
/// </summary>
private List<string> EncryptFiles(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
private List<string> EncryptFiles(BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{
var encryptionServices = buildParameters.Parameters.EncryptionServices;
@@ -45,7 +56,6 @@ namespace YooAsset.Editor
if (encryptionServices == null)
return encryptList;
UnityEngine.Debug.Log($"开始加密资源文件");
int progressValue = 0;
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
@@ -66,7 +76,7 @@ namespace YooAsset.Editor
{
byte[] bytes = encryptionServices.Encrypt(fileData);
File.WriteAllBytes(filePath, bytes);
UnityEngine.Debug.Log($"文件加密完成:{filePath}");
BuildRunner.Log($"文件加密完成:{filePath}");
}
}
@@ -75,6 +85,8 @@ namespace YooAsset.Editor
}
EditorTools.ClearProgressBar();
if(encryptList.Count == 0)
UnityEngine.Debug.LogWarning($"没有发现需要加密的文件!");
return encryptList;
}
}

View File

@@ -7,12 +7,15 @@ using UnityEditor;
namespace YooAsset.Editor
{
[TaskAttribute("获取资源构建内容")]
public class TaskGetBuildMap : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildMapContext = BuildMapHelper.SetupBuildMap();
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode);
context.SetContextObject(buildMapContext);
BuildRunner.Log("构建内容准备完毕!");
// 检测构建结果
CheckBuildMapContent(buildMapContext);
@@ -30,7 +33,7 @@ namespace YooAsset.Editor
if (isRawFile)
{
if (bundleInfo.BuildinAssets.Count != 1)
throw new Exception("The bundle does not support multiple raw asset : {bundleInfo.BundleName}");
throw new Exception($"The bundle does not support multiple raw asset : {bundleInfo.BundleName}");
continue;
}

View File

@@ -6,11 +6,12 @@ using UnityEditor;
namespace YooAsset.Editor
{
[TaskAttribute("资源构建准备工作")]
public class TaskPrepare : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
buildParameters.BeginWatch();
// 检测构建平台是否合法
@@ -26,7 +27,8 @@ namespace YooAsset.Editor
throw new Exception("输出目录不能为空");
// 增量更新时候的必要检测
if (buildParameters.Parameters.ForceRebuild == false)
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.IncrementalBuild)
{
// 检测历史版本是否存在
if (AssetBundleBuilderHelper.HasAnyPackageVersion(buildParameters.Parameters.BuildTarget, buildParameters.Parameters.OutputRoot) == false)
@@ -49,20 +51,20 @@ namespace YooAsset.Editor
}
// 如果是强制重建
if (buildParameters.Parameters.ForceRebuild)
if (buildMode == EBuildMode.ForceRebuild)
{
// 删除平台总目录
string platformDirectory = $"{buildParameters.Parameters.OutputRoot}/{buildParameters.Parameters.BuildTarget}";
if (EditorTools.DeleteDirectory(platformDirectory))
{
UnityEngine.Debug.Log($"删除平台总目录:{platformDirectory}");
BuildRunner.Log($"删除平台总目录:{platformDirectory}");
}
}
// 如果输出目录不存在
if (EditorTools.CreateDirectory(buildParameters.PipelineOutputDirectory))
{
UnityEngine.Debug.Log($"创建输出目录:{buildParameters.PipelineOutputDirectory}");
BuildRunner.Log($"创建输出目录:{buildParameters.PipelineOutputDirectory}");
}
}
}

View File

@@ -0,0 +1,174 @@
using System;
using System.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
[TaskAttribute("验证构建结果")]
public class TaskVerifyBuildResult : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
// 模拟构建模式下跳过验证
if (buildParametersContext.Parameters.BuildMode == EBuildMode.SimulateBuild)
return;
// 验证构建结果
if (buildParametersContext.Parameters.VerifyBuildingResult)
{
var unityManifestContext = context.GetContextObject<TaskBuilding.UnityManifestContext>();
VerifyingBuildingResult(context, unityManifestContext.UnityManifest);
}
}
/// <summary>
/// 验证构建结果
/// </summary>
private void VerifyingBuildingResult(BuildContext context, AssetBundleManifest unityManifest)
{
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
string[] buildedBundles = unityManifest.GetAllAssetBundles();
// 1. 过滤掉原生Bundle
List<BuildBundleInfo> expectBundles = new List<BuildBundleInfo>(buildedBundles.Length);
foreach(var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile == false)
expectBundles.Add(bundleInfo);
}
// 2. 验证数量
if (buildedBundles.Length != expectBundles.Count)
{
Debug.LogWarning($"构建过程中可能存在无效的资源导致和预期构建的Bundle数量不一致");
}
// 3. 正向验证Bundle
foreach (var bundleName in buildedBundles)
{
if (buildMapContext.IsContainsBundle(bundleName) == false)
{
throw new Exception($"Should never get here !");
}
}
// 4. 反向验证Bundle
bool isPass = true;
foreach (var expectBundle in expectBundles)
{
bool isMatch = false;
foreach (var buildedBundle in buildedBundles)
{
if (buildedBundle == expectBundle.BundleName)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
isPass = false;
Debug.LogWarning($"没有找到预期构建的Bundle文件 : {expectBundle.BundleName}");
}
}
if(isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
// 5. 验证Asset
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
int progressValue = 0;
foreach (var buildedBundle in buildedBundles)
{
string filePath = $"{buildParameters.PipelineOutputDirectory}/{buildedBundle}";
string[] allBuildinAssetPaths = GetAssetBundleAllAssets(filePath);
string[] expectBuildinAssetPaths = buildMapContext.GetBuildinAssetPaths(buildedBundle);
if (expectBuildinAssetPaths.Length != allBuildinAssetPaths.Length)
{
Debug.LogWarning($"构建的Bundle文件内的资源对象数量和预期不匹配 : {buildedBundle}");
isPass = false;
continue;
}
foreach (var buildinAssetPath in allBuildinAssetPaths)
{
var guid = AssetDatabase.AssetPathToGUID(buildinAssetPath);
if (string.IsNullOrEmpty(guid))
{
Debug.LogWarning($"无效的资源路径,请检查路径是否带有特殊符号或中文:{buildinAssetPath}");
isPass = false;
continue;
}
bool isMatch = false;
foreach (var exceptBuildAssetPath in expectBuildinAssetPaths)
{
var guidExcept = AssetDatabase.AssetPathToGUID(exceptBuildAssetPath);
if (guid == guidExcept)
{
isMatch = true;
break;
}
}
if (isMatch == false)
{
Debug.LogWarning($"在构建的Bundle文件里发现了没有匹配的资源对象{buildinAssetPath}");
isPass = false;
continue;
}
}
EditorTools.DisplayProgressBar("验证构建结果", ++progressValue, buildedBundles.Length);
}
EditorTools.ClearProgressBar();
if (isPass == false)
{
throw new Exception("构建结果验证没有通过,请参考警告日志!");
}
}
// 卸载所有加载的Bundle
BuildRunner.Log("构建结果验证成功!");
}
/// <summary>
/// 解析.manifest文件并获取资源列表
/// </summary>
private string[] GetAssetBundleAllAssets(string filePath)
{
string manifestFilePath = $"{filePath}.manifest";
List<string> assetLines = new List<string>();
using (StreamReader reader = File.OpenText(manifestFilePath))
{
string content;
bool findTarget = false;
while (null != (content = reader.ReadLine()))
{
if (content.StartsWith("Dependencies:"))
break;
if (findTarget == false && content.StartsWith("Assets:"))
findTarget = true;
if (findTarget)
{
if (content.StartsWith("- "))
{
string assetPath = content.TrimStart("- ".ToCharArray());
assetLines.Add(assetPath);
}
}
}
}
return assetLines.ToArray();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b883ac0c3c25e8143847a9326e2961cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,29 @@

namespace YooAsset.Editor
{
/// <summary>
/// 资源包流水线的构建模式
/// </summary>
public enum EBuildMode
{
/// <summary>
/// 强制重建模式
/// </summary>
ForceRebuild,
/// <summary>
/// 增量构建模式
/// </summary>
IncrementalBuild,
/// <summary>
/// 演练构建模式
/// </summary>
DryRunBuild,
/// <summary>
/// 模拟构建模式
/// </summary>
SimulateBuild,
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0b6f2523a865e454d8fa3f48a2852d5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,265 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollector
{
/// <summary>
/// 收集路径
/// 注意:支持文件夹或单个资源文件
/// </summary>
public string CollectPath = string.Empty;
/// <summary>
/// 收集器类型
/// </summary>
public ECollectorType CollectorType = ECollectorType.MainAssetCollector;
/// <summary>
/// 寻址规则类名
/// </summary>
public string AddressRuleName = nameof(AddressByFileName);
/// <summary>
/// 打包规则类名
/// </summary>
public string PackRuleName = nameof(PackDirectory);
/// <summary>
/// 过滤规则类名
/// </summary>
public string FilterRuleName = nameof(CollectAll);
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 收集器是否有效
/// </summary>
public bool IsValid()
{
if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(CollectPath) == null)
return false;
if (CollectorType == ECollectorType.None)
return false;
if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
return false;
if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
return false;
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
return false;
return true;
}
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(CollectPath) == null)
throw new Exception($"Invalid collect path : {CollectPath}");
if (CollectorType == ECollectorType.None)
throw new Exception($"{nameof(ECollectorType)}.{ECollectorType.None} is invalid in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
throw new Exception($"Invalid {nameof(IPackRule)} class type : {PackRuleName} in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
throw new Exception($"Invalid {nameof(IFilterRule)} class type : {FilterRuleName} in collector : {CollectPath}");
if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
throw new Exception($"Invalid {nameof(IAddressRule)} class type : {AddressRuleName} in collector : {CollectPath}");
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode, AssetBundleCollectorGroup group)
{
// 注意:模拟构建模式下只收集主资源
if (buildMode == EBuildMode.SimulateBuild)
{
if (CollectorType != ECollectorType.MainAssetCollector)
return new List<CollectAssetInfo>();
}
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(1000);
bool isRawAsset = PackRuleName == nameof(PackRawFile);
// 检测原生资源包的收集器类型
if (isRawAsset && CollectorType != ECollectorType.MainAssetCollector)
throw new Exception($"The raw file must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}");
if (string.IsNullOrEmpty(CollectPath))
throw new Exception($"The collect path is null or empty in group : {group.GroupName}");
// 收集打包资源
if (AssetDatabase.IsValidFolder(CollectPath))
{
string collectDirectory = CollectPath;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
foreach (string assetPath in findAssets)
{
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
{
if (result.ContainsKey(assetPath) == false)
{
var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetPath} in collector : {CollectPath}");
}
}
}
}
else
{
string assetPath = CollectPath;
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
{
var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting single asset file is invalid : {assetPath} in collector : {CollectPath}");
}
}
// 检测可寻址地址是否重复
if (AssetBundleCollectorSettingData.Setting.EnableAddressable)
{
HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
if (adressTemper.Contains(address) == false)
adressTemper.Add(address);
else
throw new Exception($"The address is existed : {address} in collector : {CollectPath}");
}
}
}
// 返回列表
return result.Values.ToList();
}
private CollectAssetInfo CreateCollectAssetInfo(EBuildMode buildMode, AssetBundleCollectorGroup group, string assetPath, bool isRawAsset)
{
string address = GetAddress(group, assetPath);
string bundleName = GetBundleName(group, assetPath);
List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, assetTags, isRawAsset);
// 注意:模拟构建模式下不需要收集依赖资源
if (buildMode == EBuildMode.SimulateBuild)
collectAssetInfo.DependAssets = new List<string>();
else
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
return collectAssetInfo;
}
private bool IsValidateAsset(string assetPath)
{
if (assetPath.StartsWith("Assets/") == false && assetPath.StartsWith("Packages/") == false)
return false;
if (AssetDatabase.IsValidFolder(assetPath))
return false;
// 注意:忽略编辑器下的类型资源
Type type = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (type == typeof(LightingDataAsset))
return false;
string ext = System.IO.Path.GetExtension(assetPath);
if (ext == "" || ext == ".dll" || ext == ".cs" || ext == ".js" || ext == ".boo" || ext == ".meta" || ext == ".cginc")
return false;
return true;
}
private bool IsCollectAsset(string assetPath)
{
// 如果收集全路径着色器
if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
return true;
}
// 根据规则设置过滤资源文件
IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
}
private string GetAddress(AssetBundleCollectorGroup group, string assetPath)
{
if (CollectorType != ECollectorType.MainAssetCollector)
return string.Empty;
IAddressRule addressRuleInstance = AssetBundleCollectorSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName));
return adressValue;
}
private string GetBundleName(AssetBundleCollectorGroup group, string assetPath)
{
// 如果自动收集所有的着色器
if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
{
string bundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
return EditorTools.GetRegularPath(bundleName).ToLower();
}
}
// 根据规则设置获取资源包名称
{
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName));
return EditorTools.GetRegularPath(bundleName).ToLower();
}
}
private List<string> GetAssetTags(AssetBundleCollectorGroup group)
{
List<string> tags = StringUtility.StringToStringList(group.AssetTags, ';');
List<string> temper = StringUtility.StringToStringList(AssetTags, ';');
tags.AddRange(temper);
return tags;
}
private List<string> GetAllDependencies(string mainAssetPath)
{
List<string> result = new List<string>();
string[] depends = AssetDatabase.GetDependencies(mainAssetPath, true);
foreach (string assetPath in depends)
{
if (IsValidateAsset(assetPath))
{
// 注意:排除主资源对象
if (assetPath != mainAssetPath)
result.Add(assetPath);
}
}
return result;
}
}
}

View File

@@ -0,0 +1,187 @@
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleCollectorConfig
{
public const string ConfigVersion = "1.0";
public const string XmlVersion = "Version";
public const string XmlCommon = "Common";
public const string XmlEnableAddressable = "AutoAddressable";
public const string XmlAutoCollectShader = "AutoCollectShader";
public const string XmlShaderBundleName = "ShaderBundleName";
public const string XmlGroup = "Group";
public const string XmlGroupName = "GroupName";
public const string XmlGroupDesc = "GroupDesc";
public const string XmlCollector = "Collector";
public const string XmlCollectPath = "CollectPath";
public const string XmlCollectorType = "CollectType";
public const string XmlAddressRule = "AddressRule";
public const string XmlPackRule = "PackRule";
public const string XmlFilterRule = "FilterRule";
public const string XmlAssetTags = "AssetTags";
/// <summary>
/// 导入XML配置表
/// </summary>
public static void ImportXmlConfig(string filePath)
{
if (File.Exists(filePath) == false)
throw new FileNotFoundException(filePath);
if (Path.GetExtension(filePath) != ".xml")
throw new Exception($"Only support xml : {filePath}");
// 加载配置文件
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
XmlElement root = xml.DocumentElement;
// 读取配置版本
string configVersion = root.GetAttribute(XmlVersion);
if(configVersion != ConfigVersion)
{
throw new Exception($"The config version is invalid : {configVersion}");
}
// 读取公共配置
bool enableAddressable = false;
bool autoCollectShaders = false;
string shaderBundleName = string.Empty;
var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (commonNodeList.Count > 0)
{
XmlElement commonElement = commonNodeList[0] as XmlElement;
if (commonElement.HasAttribute(XmlEnableAddressable) == false)
throw new Exception($"Not found attribute {XmlEnableAddressable} in {XmlCommon}");
if (commonElement.HasAttribute(XmlAutoCollectShader) == false)
throw new Exception($"Not found attribute {XmlAutoCollectShader} in {XmlCommon}");
if (commonElement.HasAttribute(XmlShaderBundleName) == false)
throw new Exception($"Not found attribute {XmlShaderBundleName} in {XmlCommon}");
enableAddressable = commonElement.GetAttribute(XmlEnableAddressable) == "True" ? true : false;
autoCollectShaders = commonElement.GetAttribute(XmlAutoCollectShader) == "True" ? true : false;
shaderBundleName = commonElement.GetAttribute(XmlShaderBundleName);
}
// 读取分组配置
List<AssetBundleCollectorGroup> groupTemper = new List<AssetBundleCollectorGroup>();
var groupNodeList = root.GetElementsByTagName(XmlGroup);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
if (groupElement.HasAttribute(XmlGroupName) == false)
throw new Exception($"Not found attribute {XmlGroupName} in {XmlGroup}");
if (groupElement.HasAttribute(XmlGroupDesc) == false)
throw new Exception($"Not found attribute {XmlGroupDesc} in {XmlGroup}");
if (groupElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlGroup}");
AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
group.GroupName = groupElement.GetAttribute(XmlGroupName);
group.GroupDesc = groupElement.GetAttribute(XmlGroupDesc);
group.AssetTags = groupElement.GetAttribute(XmlAssetTags);
groupTemper.Add(group);
// 读取收集器配置
var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlCollectPath) == false)
throw new Exception($"Not found attribute {XmlCollectPath} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlCollectorType) == false)
throw new Exception($"Not found attribute {XmlCollectorType} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAddressRule) == false)
throw new Exception($"Not found attribute {XmlAddressRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlPackRule) == false)
throw new Exception($"Not found attribute {XmlPackRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlFilterRule) == false)
throw new Exception($"Not found attribute {XmlFilterRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlCollector}");
AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectorElement.GetAttribute(XmlCollectPath);
collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(collectorElement.GetAttribute(XmlCollectorType));
collector.AddressRuleName = collectorElement.GetAttribute(XmlAddressRule);
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags); ;
group.Collectors.Add(collector);
}
}
// 保存配置数据
AssetBundleCollectorSettingData.ClearAll();
AssetBundleCollectorSettingData.Setting.EnableAddressable = enableAddressable;
AssetBundleCollectorSettingData.Setting.AutoCollectShaders = autoCollectShaders;
AssetBundleCollectorSettingData.Setting.ShadersBundleName = shaderBundleName;
AssetBundleCollectorSettingData.Setting.Groups.AddRange(groupTemper);
AssetBundleCollectorSettingData.SaveFile();
Debug.Log($"导入配置完毕!");
}
/// <summary>
/// 导出XML配置表
/// </summary>
public static void ExportXmlConfig(string savePath)
{
if (File.Exists(savePath))
File.Delete(savePath);
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<root>");
sb.AppendLine("</root>");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sb.ToString());
XmlElement root = xmlDoc.DocumentElement;
// 设置配置版本
root.SetAttribute(XmlVersion, ConfigVersion);
// 设置公共配置
var commonElement = xmlDoc.CreateElement(XmlCommon);
commonElement.SetAttribute(XmlEnableAddressable, AssetBundleCollectorSettingData.Setting.EnableAddressable.ToString());
commonElement.SetAttribute(XmlAutoCollectShader, AssetBundleCollectorSettingData.Setting.AutoCollectShaders.ToString());
commonElement.SetAttribute(XmlShaderBundleName, AssetBundleCollectorSettingData.Setting.ShadersBundleName);
root.AppendChild(commonElement);
// 设置分组配置
foreach (var group in AssetBundleCollectorSettingData.Setting.Groups)
{
var groupElement = xmlDoc.CreateElement(XmlGroup);
groupElement.SetAttribute(XmlGroupName, group.GroupName);
groupElement.SetAttribute(XmlGroupDesc, group.GroupDesc);
groupElement.SetAttribute(XmlAssetTags, group.AssetTags);
root.AppendChild(groupElement);
// 设置收集器配置
foreach (var collector in group.Collectors)
{
var collectorElement = xmlDoc.CreateElement(XmlCollector);
collectorElement.SetAttribute(XmlCollectPath, collector.CollectPath);
collectorElement.SetAttribute(XmlCollectorType, collector.CollectorType.ToString());
collectorElement.SetAttribute(XmlAddressRule, collector.AddressRuleName);
collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName);
collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName);
collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags);
groupElement.AppendChild(collectorElement);
}
}
// 生成配置文件
xmlDoc.Save(savePath);
Debug.Log($"导出配置完毕!");
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollectorGroup
{
/// <summary>
/// 分组名称
/// </summary>
public string GroupName = string.Empty;
/// <summary>
/// 分组描述
/// </summary>
public string GroupDesc = string.Empty;
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 分组激活规则
/// </summary>
public string ActiveRuleName = nameof(EnableGroup);
/// <summary>
/// 分组的收集器列表
/// </summary>
public List<AssetBundleCollector> Collectors = new List<AssetBundleCollector>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
if (AssetBundleCollectorSettingData.HasActiveRuleName(ActiveRuleName) == false)
throw new Exception($"Invalid {nameof(IActiveRule)} class type : {ActiveRuleName} in group : {GroupName}");
foreach (var collector in Collectors)
{
collector.CheckConfigError();
}
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 检测分组是否激活
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(ActiveRuleName);
if (activeRule.IsActiveGroup() == false)
{
return new List<CollectAssetInfo>();
}
// 收集打包资源
foreach (var collector in Collectors)
{
var temper = collector.GetAllCollectAssets(buildMode, this);
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in group : {GroupName}");
}
}
// 检测可寻址地址是否重复
if (AssetBundleCollectorSettingData.Setting.EnableAddressable)
{
HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
if (adressTemper.Contains(address) == false)
adressTemper.Add(address);
else
throw new Exception($"The address is existed : {address} in group : {GroupName}");
}
}
}
// 返回列表
return result.Values.ToList();
}
}
}

View File

@@ -0,0 +1,84 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleCollectorSetting : ScriptableObject
{
/// <summary>
/// 是否启用可寻址资源定位
/// </summary>
public bool EnableAddressable = false;
/// <summary>
/// 自动收集着色器
/// </summary>
public bool AutoCollectShaders = true;
/// <summary>
/// 自动收集的着色器资源包名称
/// </summary>
public string ShadersBundleName = "myshaders";
/// <summary>
/// 分组列表
/// </summary>
public List<AssetBundleCollectorGroup> Groups = new List<AssetBundleCollectorGroup>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
foreach (var group in Groups)
{
group.CheckConfigError();
}
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 收集打包资源
foreach (var group in Groups)
{
var temper = group.GetAllCollectAssets(buildMode);
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in group setting.");
}
}
// 检测可寻址地址是否重复
if (EnableAddressable)
{
HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result)
{
if (collectInfoPair.Value.CollectorType == ECollectorType.MainAssetCollector)
{
string address = collectInfoPair.Value.Address;
if (adressTemper.Contains(address) == false)
adressTemper.Add(address);
else
throw new Exception($"The address is existed : {address} in group setting.");
}
}
}
// 返回列表
return result.Values.ToList();
}
}
}

View File

@@ -1,13 +1,20 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class AssetBundleGrouperSettingData
public class AssetBundleCollectorSettingData
{
private static readonly Dictionary<string, System.Type> _cacheActiveRuleTypes = new Dictionary<string, Type>();
private static readonly Dictionary<string, IActiveRule> _cacheActiveRuleInstance = new Dictionary<string, IActiveRule>();
private static readonly Dictionary<string, System.Type> _cacheAddressRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IAddressRule> _cacheAddressRuleInstance = new Dictionary<string, IAddressRule>();
private static readonly Dictionary<string, System.Type> _cachePackRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IPackRule> _cachePackRuleInstance = new Dictionary<string, IPackRule>();
@@ -20,8 +27,8 @@ namespace YooAsset.Editor
public static bool IsDirty { private set; get; } = false;
private static AssetBundleGrouperSetting _setting = null;
public static AssetBundleGrouperSetting Setting
private static AssetBundleCollectorSetting _setting = null;
public static AssetBundleCollectorSetting Setting
{
get
{
@@ -31,6 +38,30 @@ namespace YooAsset.Editor
}
}
public static List<string> GetActiveRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cacheActiveRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static List<string> GetAddressRuleNames()
{
if (_setting == null)
LoadSettingData();
List<string> names = new List<string>();
foreach (var pair in _cacheAddressRuleTypes)
{
names.Add(pair.Key);
}
return names;
}
public static List<string> GetPackRuleNames()
{
if (_setting == null)
@@ -55,6 +86,24 @@ namespace YooAsset.Editor
}
return names;
}
public static bool HasActiveRuleName(string ruleName)
{
foreach (var pair in _cacheActiveRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasAddressRuleName(string ruleName)
{
foreach (var pair in _cacheAddressRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasPackRuleName(string ruleName)
{
foreach (var pair in _cachePackRuleTypes)
@@ -74,26 +123,13 @@ namespace YooAsset.Editor
return false;
}
/// <summary>
/// 加载配置文件
/// </summary>
private static void LoadSettingData()
{
// 加载配置文件
_setting = AssetDatabase.LoadAssetAtPath<AssetBundleGrouperSetting>(EditorDefine.AssetBundleGrouperSettingFilePath);
if (_setting == null)
{
Debug.LogWarning($"Create new {nameof(AssetBundleGrouperSetting)}.asset : {EditorDefine.AssetBundleGrouperSettingFilePath}");
_setting = ScriptableObject.CreateInstance<AssetBundleGrouperSetting>();
EditorTools.CreateFileDirectory(EditorDefine.AssetBundleGrouperSettingFilePath);
AssetDatabase.CreateAsset(Setting, EditorDefine.AssetBundleGrouperSettingFilePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
else
{
Debug.Log($"Load {nameof(AssetBundleGrouperSetting)}.asset ok");
}
_setting = EditorHelper.LoadSettingData<AssetBundleCollectorSetting>();
// IPackRule
{
@@ -106,11 +142,13 @@ namespace YooAsset.Editor
{
typeof(PackSeparately),
typeof(PackDirectory),
typeof(PackTopDirectory),
typeof(PackCollector),
typeof(PackGrouper),
typeof(PackGroup),
typeof(PackRawFile),
};
var customTypes = AssemblyUtility.GetAssignableTypes(AssemblyUtility.UnityDefaultAssemblyEditorName, typeof(IPackRule));
var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
@@ -134,7 +172,8 @@ namespace YooAsset.Editor
typeof(CollectPrefab),
typeof(CollectSprite)
};
var customTypes = AssemblyUtility.GetAssignableTypes(AssemblyUtility.UnityDefaultAssemblyEditorName, typeof(IFilterRule));
var customTypes = EditorTools.GetAssignableTypes(typeof(IFilterRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
@@ -143,6 +182,53 @@ namespace YooAsset.Editor
_cacheFilterRuleTypes.Add(type.Name, type);
}
}
// IAddressRule
{
// 清空缓存集合
_cacheAddressRuleTypes.Clear();
_cacheAddressRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(AddressByFileName),
typeof(AddressByCollectorAndFileName),
typeof(AddressByGroupAndFileName)
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IAddressRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cacheAddressRuleTypes.ContainsKey(type.Name) == false)
_cacheAddressRuleTypes.Add(type.Name, type);
}
}
// IActiveRule
{
// 清空缓存集合
_cacheActiveRuleTypes.Clear();
_cacheActiveRuleInstance.Clear();
// 获取所有类型
List<Type> types = new List<Type>(100)
{
typeof(EnableGroup),
typeof(DisableGroup),
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IActiveRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
Type type = types[i];
if (_cacheActiveRuleTypes.ContainsKey(type.Name) == false)
_cacheActiveRuleTypes.Add(type.Name, type);
}
}
}
/// <summary>
@@ -155,7 +241,7 @@ namespace YooAsset.Editor
IsDirty = false;
EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetBundleGrouperSetting)}.asset is saved!");
Debug.Log($"{nameof(AssetBundleCollectorSetting)}.asset is saved!");
}
}
@@ -166,11 +252,45 @@ namespace YooAsset.Editor
{
Setting.AutoCollectShaders = false;
Setting.ShadersBundleName = string.Empty;
Setting.Groupers.Clear();
Setting.Groups.Clear();
SaveFile();
}
// 实例类相关
public static IActiveRule GetActiveRuleInstance(string ruleName)
{
if (_cacheActiveRuleInstance.TryGetValue(ruleName, out IActiveRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheActiveRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IActiveRule)Activator.CreateInstance(type);
_cacheActiveRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IActiveRule)}类型无效:{ruleName}");
}
}
public static IAddressRule GetAddressRuleInstance(string ruleName)
{
if (_cacheAddressRuleInstance.TryGetValue(ruleName, out IAddressRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheAddressRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IAddressRule)Activator.CreateInstance(type);
_cacheAddressRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IAddressRule)}类型无效:{ruleName}");
}
}
public static IPackRule GetPackRuleInstance(string ruleName)
{
if (_cachePackRuleInstance.TryGetValue(ruleName, out IPackRule instance))
@@ -206,6 +326,13 @@ namespace YooAsset.Editor
}
}
// 可寻址编辑相关
public static void ModifyAddressable(bool enableAddressable)
{
Setting.EnableAddressable = enableAddressable;
IsDirty = true;
}
// 着色器编辑相关
public static void ModifyShader(bool isCollectAllShaders, string shadersBundleName)
{
@@ -215,48 +342,43 @@ namespace YooAsset.Editor
}
// 资源分组编辑相关
public static void CreateGrouper(string grouperName, string grouperDesc, string assetTags)
public static void CreateGroup(string groupName)
{
AssetBundleGrouper grouper = new AssetBundleGrouper();
grouper.GrouperName = grouperName;
grouper.GrouperDesc = grouperDesc;
grouper.AssetTags = assetTags;
Setting.Groupers.Add(grouper);
AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
group.GroupName = groupName;
Setting.Groups.Add(group);
IsDirty = true;
}
public static void RemoveGrouper(AssetBundleGrouper grouper)
public static void RemoveGroup(AssetBundleCollectorGroup group)
{
if (Setting.Groupers.Remove(grouper))
if (Setting.Groups.Remove(group))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove grouper : {grouper.GrouperName}");
Debug.LogWarning($"Failed remove group : {group.GroupName}");
}
}
public static void ModifyGrouper(AssetBundleGrouper grouper)
public static void ModifyGroup(AssetBundleCollectorGroup group)
{
if (grouper != null)
if (group != null)
{
IsDirty = true;
}
}
// 资源收集器编辑相关
public static void CreateCollector(AssetBundleGrouper grouper, string collectPath, string packRuleName, string filterRuleName, bool notWriteToAssetList)
public static void CreateCollector(AssetBundleCollectorGroup group, string collectPath)
{
AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectPath;
collector.PackRuleName = packRuleName;
collector.FilterRuleName = filterRuleName;
collector.NotWriteToAssetList = notWriteToAssetList;
grouper.Collectors.Add(collector);
group.Collectors.Add(collector);
IsDirty = true;
}
public static void RemoveCollector(AssetBundleGrouper grouper, AssetBundleCollector collector)
public static void RemoveCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (grouper.Collectors.Remove(collector))
if (group.Collectors.Remove(collector))
{
IsDirty = true;
}
@@ -265,9 +387,9 @@ namespace YooAsset.Editor
Debug.LogWarning($"Failed remove collector : {collector.CollectPath}");
}
}
public static void ModifyCollector(AssetBundleGrouper grouper, AssetBundleCollector collector)
public static void ModifyCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (grouper != null && collector != null)
if (group != null && collector != null)
{
IsDirty = true;
}

View File

@@ -0,0 +1,650 @@
#if UNITY_2019_4_OR_NEWER
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace YooAsset.Editor
{
public class AssetBundleCollectorWindow : EditorWindow
{
[MenuItem("YooAsset/AssetBundle Collector", false, 101)]
public static void ShowExample()
{
AssetBundleCollectorWindow window = GetWindow<AssetBundleCollectorWindow>("资源包收集工具", true, EditorDefine.DockedWindowTypes);
window.minSize = new Vector2(800, 600);
}
private List<string> _collectorTypeList;
private List<string> _activeRuleList;
private List<string> _addressRuleList;
private List<string> _packRuleList;
private List<string> _filterRuleList;
private ListView _groupListView;
private ScrollView _collectorScrollView;
private PopupField<string> _activeRulePopupField;
private Toggle _enableAddressableToogle;
private Toggle _autoCollectShaderToogle;
private TextField _shaderBundleNameTxt;
private TextField _groupNameTxt;
private TextField _groupDescTxt;
private TextField _groupAssetTagsTxt;
private VisualElement _groupContainer;
private string _lastModifyGroup = string.Empty;
public void CreateGUI()
{
Undo.undoRedoPerformed -= RefreshWindow;
Undo.undoRedoPerformed += RefreshWindow;
try
{
_collectorTypeList = new List<string>()
{
$"{nameof(ECollectorType.MainAssetCollector)}",
$"{nameof(ECollectorType.StaticAssetCollector)}",
$"{nameof(ECollectorType.DependAssetCollector)}"
};
_activeRuleList = AssetBundleCollectorSettingData.GetActiveRuleNames();
_addressRuleList = AssetBundleCollectorSettingData.GetAddressRuleNames();
_packRuleList = AssetBundleCollectorSettingData.GetPackRuleNames();
_filterRuleList = AssetBundleCollectorSettingData.GetFilterRuleNames();
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleCollectorWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
// 导入导出按钮
var exportBtn = root.Q<Button>("ExportButton");
exportBtn.clicked += ExportBtn_clicked;
var importBtn = root.Q<Button>("ImportButton");
importBtn.clicked += ImportBtn_clicked;
// 公共设置相关
_enableAddressableToogle = root.Q<Toggle>("EnableAddressable");
_enableAddressableToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyAddressable(evt.newValue);
RefreshWindow();
});
_autoCollectShaderToogle = root.Q<Toggle>("AutoCollectShader");
_autoCollectShaderToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyShader(evt.newValue, _shaderBundleNameTxt.value);
_shaderBundleNameTxt.SetEnabled(evt.newValue);
});
_shaderBundleNameTxt = root.Q<TextField>("ShaderBundleName");
_shaderBundleNameTxt.RegisterValueChangedCallback(evt =>
{
AssetBundleCollectorSettingData.ModifyShader(_autoCollectShaderToogle.value, evt.newValue);
});
// 分组列表相关
_groupListView = root.Q<ListView>("GroupListView");
_groupListView.makeItem = MakeGroupListViewItem;
_groupListView.bindItem = BindGroupListViewItem;
#if UNITY_2020_1_OR_NEWER
_groupListView.onSelectionChange += GroupListView_onSelectionChange;
#else
_groupListView.onSelectionChanged += GroupListView_onSelectionChange;
#endif
// 分组添加删除按钮
var groupAddContainer = root.Q("GroupAddContainer");
{
var addBtn = groupAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddGroupBtn_clicked;
var removeBtn = groupAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemoveGroupBtn_clicked;
}
// 分组容器
_groupContainer = root.Q("GroupContainer");
// 分组名称
_groupNameTxt = root.Q<TextField>("GroupName");
_groupNameTxt.RegisterValueChangedCallback(evt =>
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup != null)
{
selectGroup.GroupName = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
}
});
// 分组备注
_groupDescTxt = root.Q<TextField>("GroupDesc");
_groupDescTxt.RegisterValueChangedCallback(evt =>
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup != null)
{
selectGroup.GroupDesc = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
}
});
// 分组的资源标签
_groupAssetTagsTxt = root.Q<TextField>("GroupAssetTags");
_groupAssetTagsTxt.RegisterValueChangedCallback(evt =>
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup != null)
{
selectGroup.AssetTags = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
}
});
// 收集列表相关
_collectorScrollView = root.Q<ScrollView>("CollectorScrollView");
_collectorScrollView.style.height = new Length(100, LengthUnit.Percent);
_collectorScrollView.viewDataKey = "scrollView";
// 收集器创建按钮
var collectorAddContainer = root.Q("CollectorAddContainer");
{
var addBtn = collectorAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddCollectorBtn_clicked;
}
// 分组激活规则
var activeRuleContainer = root.Q("ActiveRuleContainer");
{
_activeRulePopupField = new PopupField<string>("Active Rule", _activeRuleList, 0);
_activeRulePopupField.name = "ActiveRuleMaskField";
_activeRulePopupField.style.unityTextAlign = TextAnchor.MiddleLeft;
activeRuleContainer.Add(_activeRulePopupField);
_activeRulePopupField.RegisterValueChangedCallback(evt =>
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup != null)
{
selectGroup.ActiveRuleName = evt.newValue;
AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
FillGroupViewData();
}
});
}
// 刷新窗体
RefreshWindow();
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
// 注意:清空所有撤销操作
Undo.ClearAll();
if (AssetBundleCollectorSettingData.IsDirty)
AssetBundleCollectorSettingData.SaveFile();
}
private void RefreshWindow()
{
_enableAddressableToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.EnableAddressable);
_autoCollectShaderToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetEnabled(AssetBundleCollectorSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShadersBundleName);
_groupContainer.visible = false;
FillGroupViewData();
}
private void ExportBtn_clicked()
{
string resultPath = EditorTools.OpenFolderPanel("Export XML", "Assets/");
if (resultPath != null)
{
AssetBundleCollectorConfig.ExportXmlConfig($"{resultPath}/{nameof(AssetBundleCollectorConfig)}.xml");
}
}
private void ImportBtn_clicked()
{
string resultPath = EditorTools.OpenFilePath("Import XML", "Assets/", "xml");
if (resultPath != null)
{
AssetBundleCollectorConfig.ImportXmlConfig(resultPath);
RefreshWindow();
}
}
// 分组列表相关
private void FillGroupViewData()
{
_groupListView.Clear();
_groupListView.ClearSelection();
_groupListView.itemsSource = AssetBundleCollectorSettingData.Setting.Groups;
_groupListView.Rebuild();
for (int index = 0; index < AssetBundleCollectorSettingData.Setting.Groups.Count; index++)
{
var group = AssetBundleCollectorSettingData.Setting.Groups[index];
if (group.GroupName == _lastModifyGroup)
{
_groupListView.selectedIndex = index;
break;
}
}
}
private VisualElement MakeGroupListViewItem()
{
VisualElement element = new VisualElement();
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.flexGrow = 1f;
label.style.height = 20f;
element.Add(label);
}
return element;
}
private void BindGroupListViewItem(VisualElement element, int index)
{
var group = AssetBundleCollectorSettingData.Setting.Groups[index];
// Group Name
var textField1 = element.Q<Label>("Label1");
if (string.IsNullOrEmpty(group.GroupDesc))
textField1.text = group.GroupName;
else
textField1.text = $"{group.GroupName} ({group.GroupDesc})";
// 激活状态
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(group.ActiveRuleName);
bool isActive = activeRule.IsActiveGroup();
textField1.SetEnabled(isActive);
}
private void GroupListView_onSelectionChange(IEnumerable<object> objs)
{
FillCollectorViewData();
}
private void AddGroupBtn_clicked()
{
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddGroup");
AssetBundleCollectorSettingData.CreateGroup("Default Group");
FillGroupViewData();
}
private void RemoveGroupBtn_clicked()
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveGroup");
AssetBundleCollectorSettingData.RemoveGroup(selectGroup);
FillGroupViewData();
}
// 收集列表相关
private void FillCollectorViewData()
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
{
_groupContainer.visible = false;
return;
}
_lastModifyGroup = selectGroup.GroupName;
_groupContainer.visible = true;
_activeRulePopupField.SetValueWithoutNotify(selectGroup.ActiveRuleName);
_groupNameTxt.SetValueWithoutNotify(selectGroup.GroupName);
_groupDescTxt.SetValueWithoutNotify(selectGroup.GroupDesc);
_groupAssetTagsTxt.SetValueWithoutNotify(selectGroup.AssetTags);
// 填充数据
_collectorScrollView.Clear();
for (int i = 0; i < selectGroup.Collectors.Count; i++)
{
VisualElement element = MakeCollectorListViewItem();
BindCollectorListViewItem(element, i);
_collectorScrollView.Add(element);
}
}
private VisualElement MakeCollectorListViewItem()
{
VisualElement element = new VisualElement();
VisualElement elementTop = new VisualElement();
elementTop.style.flexDirection = FlexDirection.Row;
element.Add(elementTop);
VisualElement elementBottom = new VisualElement();
elementBottom.style.flexDirection = FlexDirection.Row;
element.Add(elementBottom);
VisualElement elementFoldout = new VisualElement();
elementFoldout.style.flexDirection = FlexDirection.Row;
element.Add(elementFoldout);
VisualElement elementSpace = new VisualElement();
elementSpace.style.flexDirection = FlexDirection.Column;
element.Add(elementSpace);
// Top VisualElement
{
var button = new Button();
button.name = "Button1";
button.text = "-";
button.style.unityTextAlign = TextAnchor.MiddleCenter;
button.style.flexGrow = 0f;
elementTop.Add(button);
}
{
var objectField = new ObjectField();
objectField.name = "ObjectField1";
objectField.label = "Collector";
objectField.objectType = typeof(UnityEngine.Object);
objectField.style.unityTextAlign = TextAnchor.MiddleLeft;
objectField.style.flexGrow = 1f;
elementTop.Add(objectField);
var label = objectField.Q<Label>();
label.style.minWidth = 63;
}
// Bottom VisualElement
{
var label = new Label();
label.style.width = 90;
elementBottom.Add(label);
}
{
var popupField = new PopupField<string>(_collectorTypeList, 0);
popupField.name = "PopupField0";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
if (_enableAddressableToogle.value)
{
var popupField = new PopupField<string>(_addressRuleList, 0);
popupField.name = "PopupField1";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 200;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<string>(_packRuleList, 0);
popupField.name = "PopupField2";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<string>(_filterRuleList, 0);
popupField.name = "PopupField3";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var textField = new TextField();
textField.name = "TextField1";
textField.label = "Tags";
textField.style.width = 100;
textField.style.marginLeft = 20;
textField.style.flexGrow = 1;
elementBottom.Add(textField);
var label = textField.Q<Label>();
label.style.minWidth = 40;
}
// Foldout VisualElement
{
var label = new Label();
label.style.width = 90;
elementFoldout.Add(label);
}
{
var foldout = new Foldout();
foldout.name = "Foldout1";
foldout.value = false;
foldout.text = "Main Assets";
elementFoldout.Add(foldout);
}
// Space VisualElement
{
var label = new Label();
label.style.height = 10;
elementSpace.Add(label);
}
return element;
}
private void BindCollectorListViewItem(VisualElement element, int index)
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
var collector = selectGroup.Collectors[index];
var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath);
if (collectObject != null)
collectObject.name = collector.CollectPath;
// Foldout
var foldout = element.Q<Foldout>("Foldout1");
foldout.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
RefreshFoldout(foldout, selectGroup, collector);
else
foldout.Clear();
});
// Remove Button
var removeBtn = element.Q<Button>("Button1");
removeBtn.clicked += () =>
{
RemoveCollectorBtn_clicked(collector);
};
// Collector Path
var objectField1 = element.Q<ObjectField>("ObjectField1");
objectField1.SetValueWithoutNotify(collectObject);
objectField1.RegisterValueChangedCallback(evt =>
{
collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue);
objectField1.value.name = collector.CollectPath;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Collector Type
var popupField0 = element.Q<PopupField<string>>("PopupField0");
popupField0.index = GetCollectorTypeIndex(collector.CollectorType.ToString());
popupField0.RegisterValueChangedCallback(evt =>
{
collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(evt.newValue);
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Address Rule
var popupField1 = element.Q<PopupField<string>>("PopupField1");
if (popupField1 != null)
{
popupField1.index = GetAddressRuleIndex(collector.AddressRuleName);
popupField1.RegisterValueChangedCallback(evt =>
{
collector.AddressRuleName = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
}
// Pack Rule
var popupField2 = element.Q<PopupField<string>>("PopupField2");
popupField2.index = GetPackRuleIndex(collector.PackRuleName);
popupField2.RegisterValueChangedCallback(evt =>
{
collector.PackRuleName = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Filter Rule
var popupField3 = element.Q<PopupField<string>>("PopupField3");
popupField3.index = GetFilterRuleIndex(collector.FilterRuleName);
popupField3.RegisterValueChangedCallback(evt =>
{
collector.FilterRuleName = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
});
// Tags
var textFiled1 = element.Q<TextField>("TextField1");
textFiled1.SetValueWithoutNotify(collector.AssetTags);
textFiled1.RegisterValueChangedCallback(evt =>
{
collector.AssetTags = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
});
}
private void RefreshFoldout(Foldout foldout, AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
// 清空旧元素
foldout.Clear();
if (collector.IsValid() == false)
{
Debug.LogWarning($"The collector is invalid : {collector.CollectPath} in group : {group.GroupName}");
return;
}
if (collector.CollectorType == ECollectorType.MainAssetCollector || collector.CollectorType == ECollectorType.StaticAssetCollector)
{
List<CollectAssetInfo> collectAssetInfos = null;
try
{
collectAssetInfos = collector.GetAllCollectAssets(EBuildMode.DryRunBuild, group);
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
if (collectAssetInfos != null)
{
foreach (var collectAssetInfo in collectAssetInfos)
{
VisualElement elementRow = new VisualElement();
elementRow.style.flexDirection = FlexDirection.Row;
foldout.Add(elementRow);
string showInfo = collectAssetInfo.AssetPath;
if (_enableAddressableToogle.value)
{
IAddressRule instance = AssetBundleCollectorSettingData.GetAddressRuleInstance(collector.AddressRuleName);
AddressRuleData ruleData = new AddressRuleData(collectAssetInfo.AssetPath, collector.CollectPath, group.GroupName);
string addressValue = instance.GetAssetAddress(ruleData);
showInfo = $"[{addressValue}] {showInfo}";
}
var label = new Label();
label.text = showInfo;
label.style.width = 300;
label.style.marginLeft = 0;
label.style.flexGrow = 1;
elementRow.Add(label);
}
}
}
}
private void AddCollectorBtn_clicked()
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddCollector");
AssetBundleCollectorSettingData.CreateCollector(selectGroup, string.Empty);
FillCollectorViewData();
}
private void RemoveCollectorBtn_clicked(AssetBundleCollector selectCollector)
{
var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGroup == null)
return;
if (selectCollector == null)
return;
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveCollector");
AssetBundleCollectorSettingData.RemoveCollector(selectGroup, selectCollector);
FillCollectorViewData();
}
private int GetCollectorTypeIndex(string typeName)
{
for (int i = 0; i < _collectorTypeList.Count; i++)
{
if (_collectorTypeList[i] == typeName)
return i;
}
return 0;
}
private int GetAddressRuleIndex(string ruleName)
{
for (int i = 0; i < _addressRuleList.Count; i++)
{
if (_addressRuleList[i] == ruleName)
return i;
}
return 0;
}
private int GetPackRuleIndex(string ruleName)
{
for (int i = 0; i < _packRuleList.Count; i++)
{
if (_packRuleList[i] == ruleName)
return i;
}
return 0;
}
private int GetFilterRuleIndex(string ruleName)
{
for (int i = 0; i < _filterRuleList.Count; i++)
{
if (_filterRuleList[i] == ruleName)
return i;
}
return 0;
}
}
}
#endif

View File

@@ -1,31 +1,31 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<uie:Toolbar name="Toolbar" style="display: flex;">
<uie:ToolbarSearchField focusable="true" name="SearchField" style="width: 300px; flex-grow: 1;" />
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;">
<ui:Button text="导出" display-tooltip-when-elided="true" name="ExportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
<ui:Button text="导入" display-tooltip-when-elided="true" name="ImportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
</uie:Toolbar>
<ui:VisualElement name="ContentContainer" style="flex-grow: 1; flex-direction: row;">
<ui:VisualElement name="LeftContainer" style="width: 200px; flex-grow: 0; background-color: rgb(67, 67, 67); border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:ListView focusable="true" name="GrouperListView" item-height="20" style="flex-grow: 1;" />
<ui:VisualElement name="GrouperAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:ListView focusable="true" name="GroupListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="GroupAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:Button text=" - " display-tooltip-when-elided="true" name="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement name="RightContainer" style="flex-direction: column; flex-grow: 1;">
<ui:VisualElement name="ShaderContainer" style="height: 30px; background-color: rgb(67, 67, 67); flex-direction: row; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:VisualElement name="PublicContainer" style="height: 30px; background-color: rgb(67, 67, 67); flex-direction: row; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:Toggle label="Enable Addressable" name="EnableAddressable" style="width: 196px; -unity-text-align: middle-left;" />
<ui:Toggle label="Auto Collect Shaders" name="AutoCollectShader" style="width: 196px; -unity-text-align: middle-left;" />
<ui:TextField picking-mode="Ignore" label="Shader Bundle Name" name="ShaderBundleName" style="flex-grow: 1; -unity-text-align: middle-left;" />
</ui:VisualElement>
<ui:VisualElement name="GrouperContainer" style="flex-grow: 1; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:TextField picking-mode="Ignore" label="Grouper Name" name="GrouperName" />
<ui:TextField picking-mode="Ignore" label="Grouper Desc" name="GrouperDesc" />
<ui:TextField picking-mode="Ignore" label="Grouper Asset Tags" name="GrouperAssetTags" />
<ui:VisualElement name="GroupContainer" style="flex-grow: 1; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:VisualElement name="ActiveRuleContainer" style="height: 20px;" />
<ui:TextField picking-mode="Ignore" label="Group Name" name="GroupName" />
<ui:TextField picking-mode="Ignore" label="Group Desc" name="GroupDesc" />
<ui:TextField picking-mode="Ignore" label="Group Asset Tags" name="GroupAssetTags" />
<ui:VisualElement name="CollectorAddContainer" style="height: 20px; flex-direction: row-reverse;">
<ui:Button text=" - " display-tooltip-when-elided="true" name="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
<ui:Button text="[ + ]" display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
<ui:ListView focusable="true" name="CollectorListView" item-height="50" style="flex-grow: 1;" />
<ui:ScrollView name="CollectorScrollView" style="flex-grow: 1;" />
</ui:VisualElement>
</ui:VisualElement>
</ui:VisualElement>

View File

@@ -5,11 +5,21 @@ namespace YooAsset.Editor
{
public class CollectAssetInfo
{
/// <summary>
/// 收集器类型
/// </summary>
public ECollectorType CollectorType { private set; get; }
/// <summary>
/// 资源包名称
/// </summary>
public string BundleName { private set; get; }
/// <summary>
/// 可寻址地址
/// </summary>
public string Address { private set; get; }
/// <summary>
/// 资源路径
/// </summary>
@@ -25,32 +35,20 @@ namespace YooAsset.Editor
/// </summary>
public bool IsRawAsset { private set; get; }
/// <summary>
/// 不写入资源列表
/// </summary>
public bool NotWriteToAssetList { private set; get; }
/// <summary>
/// 依赖的资源列表
/// </summary>
public List<string> DependAssets = new List<string>();
public CollectAssetInfo(string bundleName, string assetPath, List<string> assetTags, bool isRawAsset, bool notWriteToAssetList)
public CollectAssetInfo(ECollectorType collectorType, string bundleName, string address, string assetPath, List<string> assetTags, bool isRawAsset)
{
CollectorType = collectorType;
BundleName = bundleName;
Address = address;
AssetPath = assetPath;
AssetTags = assetTags;
IsRawAsset = isRawAsset;
NotWriteToAssetList = notWriteToAssetList;
}
public CollectAssetInfo(string assetPath, List<string> assetTags, bool isRawAsset, bool notWriteToAssetList)
{
BundleName = string.Empty;
AssetPath = assetPath;
AssetTags = assetTags;
IsRawAsset = isRawAsset;
NotWriteToAssetList = notWriteToAssetList;
}
}
}

View File

@@ -0,0 +1,25 @@

namespace YooAsset.Editor
{
/// <summary>
/// 启用分组
/// </summary>
public class EnableGroup : IActiveRule
{
public bool IsActiveGroup()
{
return true;
}
}
/// <summary>
/// 禁用分组
/// </summary>
public class DisableGroup : IActiveRule
{
public bool IsActiveGroup()
{
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2cfd65b3b7663b247b2df16077f4ef17
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,40 @@
using System.IO;
namespace YooAsset.Editor
{
/// <summary>
/// 以文件名为定位地址
/// </summary>
public class AddressByFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return Path.GetFileNameWithoutExtension(data.AssetPath);
}
}
/// <summary>
/// 以组名+文件名为定位地址
/// </summary>
public class AddressByGroupAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
return $"{data.GroupName}_{fileName}";
}
}
/// <summary>
/// 以收集器名+文件名为定位地址
/// </summary>
public class AddressByCollectorAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
string collectorName = Path.GetFileNameWithoutExtension(data.CollectPath);
return $"{collectorName}_{fileName}";
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6df37bfd87103a54ca60c0c467a5f33b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -44,10 +44,19 @@ namespace YooAsset.Editor
{
public bool IsCollectAsset(FilterRuleData data)
{
if (AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath) == typeof(Sprite))
return true;
var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
if(mainAssetType == typeof(Texture2D))
{
var texImporter = AssetImporter.GetAtPath(data.AssetPath) as TextureImporter;
if (texImporter != null && texImporter.textureType == TextureImporterType.Sprite)
return true;
else
return false;
}
else
{
return false;
}
}
}
}

View File

@@ -7,30 +7,66 @@ namespace YooAsset.Editor
/// <summary>
/// 以文件路径作为资源包名
/// 注意:每个文件独自打资源包
/// 例如:收集器路径为 "Assets/UIPanel"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop/image/backgroud.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop/view/main.bundle"
/// </summary>
public class PackSeparately : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
{
return StringUtility.RemoveExtension(data.AssetPath); //"Assets/Config/test.txt" --> "Assets/Config/test"
return StringUtility.RemoveExtension(data.AssetPath);
}
}
/// <summary>
/// 以父类文件夹路径作为资源包名
/// 注意:文件夹下所有文件打进一个资源包
/// 例如:收集器路径为 "Assets/UIPanel"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop/image.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop/view.bundle"
/// </summary>
public class PackDirectory : IPackRule
{
public static PackDirectory StaticPackRule = new PackDirectory();
string IPackRule.GetBundleName(PackRuleData data)
{
return Path.GetDirectoryName(data.AssetPath); //"Assets/Config/test.txt" --> "Assets/Config"
return Path.GetDirectoryName(data.AssetPath);
}
}
/// <summary>
/// 以收集器路径下顶级文件夹为资源包名
/// 注意:文件夹下所有文件打进一个资源包
/// 例如:收集器路径为 "Assets/UIPanel"
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets/uipanel/shop.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets/uipanel/shop.bundle"
/// </summary>
public class PackTopDirectory : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
{
string assetPath = data.AssetPath.Replace(data.CollectPath, string.Empty);
assetPath = assetPath.TrimStart('/');
string[] splits = assetPath.Split('/');
if (splits.Length > 0)
{
if (Path.HasExtension(splits[0]))
throw new Exception($"Not found root directory : {assetPath}");
string bundleName = $"{data.CollectPath}/{splits[0]}";
return bundleName;
}
else
{
throw new Exception($"Not found root directory : {assetPath}");
}
}
}
/// <summary>
/// 以收集器路径作为资源包名
/// 注意:收集器下所有文件打进一个资源包
/// 注意:收集所有文件打进一个资源包
/// </summary>
public class PackCollector : IPackRule
{
@@ -42,13 +78,13 @@ namespace YooAsset.Editor
/// <summary>
/// 以分组名称作为资源包名
/// 注意:分组内所有文件打进一个资源包
/// 注意:收集的所有文件打进一个资源包
/// </summary>
public class PackGrouper : IPackRule
public class PackGroup : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
{
return data.GrouperName;
return data.GroupName;
}
}

View File

@@ -0,0 +1,29 @@
using System;
namespace YooAsset.Editor
{
[Serializable]
public enum ECollectorType
{
/// <summary>
/// 收集参与打包的主资源对象,并写入到资源清单的资源列表里(可以通过代码加载)。
/// </summary>
MainAssetCollector,
/// <summary>
/// 收集参与打包的主资源对象,但不写入到资源清单的资源列表里(无法通过代码加载)。
/// </summary>
StaticAssetCollector,
/// <summary>
/// 收集参与打包的依赖资源对象,但不写入到资源清单的资源列表里(无法通过代码加载)。
/// 注意:如果依赖资源对象没有被主资源对象引用,则不参与打包构建。
/// </summary>
DependAssetCollector,
/// <summary>
/// 该收集器类型不能被设置
/// </summary>
None,
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4bbef9cb5c1a40b41a28a65df3449abe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,14 @@

namespace YooAsset.Editor
{
/// <summary>
/// 资源分组激活规则接口
/// </summary>
public interface IActiveRule
{
/// <summary>
/// 是否激活分组
/// </summary>
bool IsActiveGroup();
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aed5a1a6733b7d44ca4f6149ed5a2bb8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,25 @@

namespace YooAsset.Editor
{
public struct AddressRuleData
{
public string AssetPath;
public string CollectPath;
public string GroupName;
public AddressRuleData(string assetPath, string collectPath, string groupName)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
}
}
/// <summary>
/// 寻址规则接口
/// </summary>
public interface IAddressRule
{
string GetAssetAddress(AddressRuleData data);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 426a4ff47699b6844946329f54a89128
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -5,19 +5,19 @@ namespace YooAsset.Editor
{
public string AssetPath;
public string CollectPath;
public string GrouperName;
public string GroupName;
public PackRuleData(string assetPath)
{
AssetPath = assetPath;
CollectPath = string.Empty;
GrouperName = string.Empty;
GroupName = string.Empty;
}
public PackRuleData(string assetPath, string collectPath, string grouperName)
public PackRuleData(string assetPath, string collectPath, string groupName)
{
AssetPath = assetPath;
CollectPath = collectPath;
GrouperName = grouperName;
GroupName = groupName;
}
}

View File

@@ -1,141 +1,298 @@
#if UNITY_2019_4_OR_NEWER
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor.Networking.PlayerConnection;
using UnityEngine.Networking.PlayerConnection;
namespace YooAsset.Editor
{
public class AssetBundleDebuggerWindow : EditorWindow
{
[MenuItem("YooAsset/AssetBundle Debugger", false, 104)]
public static void ShowExample()
{
AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>();
wnd.titleContent = new GUIContent("资源包调试工具");
wnd.minSize = new Vector2(800, 600);
}
public class AssetBundleDebuggerWindow : EditorWindow
{
[MenuItem("YooAsset/AssetBundle Debugger", false, 104)]
public static void ShowExample()
{
AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>("资源包调试工具", true, EditorDefine.DockedWindowTypes);
wnd.minSize = new Vector2(800, 600);
}
/// <summary>
/// 视图模式
/// </summary>
private enum EViewMode
{
/// <summary>
/// 内存视图
/// </summary>
MemoryView,
/// <summary>
/// 视图模式
/// </summary>
private enum EViewMode
{
/// <summary>
/// 内存视图
/// </summary>
MemoryView,
/// <summary>
/// 资源对象视图
/// </summary>
AssetView,
/// <summary>
/// 资源对象视图
/// </summary>
AssetView,
/// <summary>
/// 资源包视图
/// </summary>
BundleView,
}
private ToolbarMenu _viewModeMenu;
private AssetListDebuggerViewer _assetListViewer;
private BundleListDebuggerViewer _bundleListViewer;
private EViewMode _viewMode;
private readonly DebugReport _debugReport = new DebugReport();
private string _searchKeyWord;
/// <summary>
/// 资源包视图
/// </summary>
BundleView,
}
public void CreateGUI()
{
VisualElement root = rootVisualElement;
private readonly Dictionary<int, RemotePlayerSession> _playerSessions = new Dictionary<int, RemotePlayerSession>();
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/{nameof(AssetBundleDebuggerWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleDebuggerWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
private Label _playerName;
private ToolbarMenu _viewModeMenu;
private SliderInt _frameSlider;
private DebuggerAssetListViewer _assetListViewer;
private DebuggerBundleListViewer _bundleListViewer;
// 采样按钮
var sampleBtn = root.Q<Button>("SampleButton");
sampleBtn.clicked += SampleBtn_onClick;
private EViewMode _viewMode;
private string _searchKeyWord;
private DebugReport _currentReport;
private RemotePlayerSession _currentPlayerSession;
private int _rangeIndex = 0;
// 视口模式菜单
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
//_viewModeMenu.menu.AppendAction(EViewMode.MemoryView.ToString(), ViewModeMenuAction0, ViewModeMenuFun0);
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), ViewModeMenuAction1, ViewModeMenuFun1);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), ViewModeMenuAction2, ViewModeMenuFun2);
// 搜索栏
var searchField = root.Q<ToolbarSearchField>("SearchField");
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
public void CreateGUI()
{
try
{
VisualElement root = rootVisualElement;
// 加载视图
_assetListViewer = new AssetListDebuggerViewer();
_assetListViewer.InitViewer();
// 加载布局文件
var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleDebuggerWindow>();
if (visualAsset == null)
return;
// 加载视图
_bundleListViewer = new BundleListDebuggerViewer();
_bundleListViewer.InitViewer();
visualAsset.CloneTree(root);
// 显示视图
_viewMode = EViewMode.AssetView;
_viewModeMenu.text = EViewMode.AssetView.ToString();
_assetListViewer.AttachParent(root);
}
private void SampleBtn_onClick()
{
YooAssets.GetDebugReport(_debugReport);
_assetListViewer.FillViewData(_debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(_debugReport, _searchKeyWord);
}
private void OnSearchKeyWordChange(ChangeEvent<string> e)
{
_searchKeyWord = e.newValue;
_assetListViewer.FillViewData(_debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(_debugReport, _searchKeyWord);
}
private void ViewModeMenuAction1(DropdownMenuAction action)
{
if (_viewMode != EViewMode.AssetView)
{
_viewMode = EViewMode.AssetView;
VisualElement root = this.rootVisualElement;
_viewModeMenu.text = EViewMode.AssetView.ToString();
_assetListViewer.AttachParent(root);
_bundleListViewer.DetachParent();
}
}
private void ViewModeMenuAction2(DropdownMenuAction action)
{
if (_viewMode != EViewMode.BundleView)
{
_viewMode = EViewMode.BundleView;
VisualElement root = this.rootVisualElement;
_viewModeMenu.text = EViewMode.BundleView.ToString();
_assetListViewer.DetachParent();
_bundleListViewer.AttachParent(root);
}
}
private DropdownMenuAction.Status ViewModeMenuFun1(DropdownMenuAction action)
{
if (_viewMode == EViewMode.AssetView)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
}
private DropdownMenuAction.Status ViewModeMenuFun2(DropdownMenuAction action)
{
if (_viewMode == EViewMode.BundleView)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
}
}
// 采样按钮
var sampleBtn = root.Q<Button>("SampleButton");
sampleBtn.clicked += SampleBtn_onClick;
// 用户列表菜单
_playerName = root.Q<Label>("PlayerName");
_playerName.text = "Editor player";
// 视口模式菜单
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), OnViewModeMenuChange, OnViewModeMenuStatusUpdate, EViewMode.AssetView);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), OnViewModeMenuChange, OnViewModeMenuStatusUpdate, EViewMode.BundleView);
_viewModeMenu.text = EViewMode.AssetView.ToString();
// 搜索栏
var searchField = root.Q<ToolbarSearchField>("SearchField");
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
// 帧数相关
{
_frameSlider = root.Q<SliderInt>("FrameSlider");
_frameSlider.label = "Frame:";
_frameSlider.highValue = 0;
_frameSlider.lowValue = 0;
_frameSlider.value = 0;
_frameSlider.RegisterValueChangedCallback(evt =>
{
OnFrameSliderChange(evt.newValue);
});
var frameLast = root.Q<ToolbarButton>("FrameLast");
frameLast.clicked += OnFrameLast_clicked;
var frameNext = root.Q<ToolbarButton>("FrameNext");
frameNext.clicked += OnFrameNext_clicked;
var frameClear = root.Q<ToolbarButton>("FrameClear");
frameClear.clicked += OnFrameClear_clicked;
}
// 加载视图
_assetListViewer = new DebuggerAssetListViewer();
_assetListViewer.InitViewer();
// 加载视图
_bundleListViewer = new DebuggerBundleListViewer();
_bundleListViewer.InitViewer();
// 显示视图
_viewMode = EViewMode.AssetView;
_assetListViewer.AttachParent(root);
// 远程调试
EditorConnection.instance.Initialize();
EditorConnection.instance.RegisterConnection(OnHandleConnectionEvent);
EditorConnection.instance.RegisterDisconnection(OnHandleDisconnectionEvent);
EditorConnection.instance.Register(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
RemoteDebuggerInRuntime.EditorHandleDebugReportCallback = OnHandleDebugReport;
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
// 远程调试
EditorConnection.instance.UnregisterConnection(OnHandleConnectionEvent);
EditorConnection.instance.UnregisterDisconnection(OnHandleDisconnectionEvent);
EditorConnection.instance.Unregister(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
_playerSessions.Clear();
}
private void OnHandleConnectionEvent(int playerId)
{
Debug.Log($"Game player connection : {playerId}");
_playerName.text = $"Connected player : {playerId}";
}
private void OnHandleDisconnectionEvent(int playerId)
{
Debug.Log($"Game player disconnection : {playerId}");
_playerName.text = $"Disconneced player : {playerId}";
}
private void OnHandlePlayerMessage(MessageEventArgs args)
{
var debugReport = DebugReport.Deserialize(args.data);
OnHandleDebugReport(args.playerId, debugReport);
}
private void OnHandleDebugReport(int playerId, DebugReport debugReport)
{
Debug.Log($"Handle player {playerId} debug report !");
_currentPlayerSession = GetOrCreatePlayerSession(playerId);
_currentPlayerSession.AddDebugReport(debugReport);
_frameSlider.highValue = _currentPlayerSession.MaxRangeValue;
_frameSlider.value = _currentPlayerSession.MaxRangeValue;
UpdateFrameView(_currentPlayerSession);
}
private void OnFrameSliderChange(int sliderValue)
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(sliderValue); ;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameLast_clicked()
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(_rangeIndex - 1);
_frameSlider.value = _rangeIndex;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameNext_clicked()
{
if (_currentPlayerSession != null)
{
_rangeIndex = _currentPlayerSession.ClampRangeIndex(_rangeIndex + 1);
_frameSlider.value = _rangeIndex;
UpdateFrameView(_currentPlayerSession, _rangeIndex);
}
}
private void OnFrameClear_clicked()
{
if (_currentPlayerSession != null)
{
_frameSlider.label = $"Frame:";
_frameSlider.value = 0;
_frameSlider.lowValue = 0;
_frameSlider.highValue = 0;
_currentPlayerSession.ClearDebugReport();
_assetListViewer.ClearView();
_bundleListViewer.ClearView();
}
}
private RemotePlayerSession GetOrCreatePlayerSession(int playerId)
{
if (_playerSessions.TryGetValue(playerId, out RemotePlayerSession session))
{
return session;
}
else
{
RemotePlayerSession newSession = new RemotePlayerSession(playerId);
_playerSessions.Add(playerId, newSession);
return newSession;
}
}
private void UpdateFrameView(RemotePlayerSession playerSession)
{
if (playerSession != null)
{
UpdateFrameView(playerSession, playerSession.MaxRangeValue);
}
}
private void UpdateFrameView(RemotePlayerSession playerSession, int rangeIndex)
{
if (playerSession == null)
return;
var debugReport = playerSession.GetDebugReport(rangeIndex);
if (debugReport != null)
{
_currentReport = debugReport;
_frameSlider.label = $"Frame: {debugReport.FrameCount}";
_assetListViewer.FillViewData(debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(debugReport, _searchKeyWord);
}
}
private void SampleBtn_onClick()
{
// 发送采集数据的命令
RemoteCommand command = new RemoteCommand();
command.CommandType = (int)ERemoteCommand.SampleOnce;
command.CommandParam = string.Empty;
byte[] data = RemoteCommand.Serialize(command);
EditorConnection.instance.Send(RemoteDebuggerDefine.kMsgSendEditorToPlayer, data);
RemoteDebuggerInRuntime.EditorRequestDebugReport();
}
private void OnSearchKeyWordChange(ChangeEvent<string> e)
{
_searchKeyWord = e.newValue;
if (_currentReport != null)
{
_assetListViewer.FillViewData(_currentReport, _searchKeyWord);
_bundleListViewer.FillViewData(_currentReport, _searchKeyWord);
}
}
private void OnViewModeMenuChange(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode != viewMode)
{
_viewMode = viewMode;
VisualElement root = this.rootVisualElement;
_viewModeMenu.text = viewMode.ToString();
if (viewMode == EViewMode.AssetView)
{
_assetListViewer.AttachParent(root);
_bundleListViewer.DetachParent();
}
else if (viewMode == EViewMode.BundleView)
{
_assetListViewer.DetachParent();
_bundleListViewer.AttachParent(root);
}
else
{
throw new NotImplementedException(viewMode.ToString());
}
}
}
private DropdownMenuAction.Status OnViewModeMenuStatusUpdate(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode == viewMode)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
}
}
}
#endif

View File

@@ -1,7 +1,14 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<uie:Toolbar name="Toolbar" style="display: flex;">
<uie:ToolbarButton text="刷新" display-tooltip-when-elided="true" name="SampleButton" style="width: 70px; background-color: rgb(15, 118, 31); -unity-text-align: middle-center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-left-width: 1px; border-right-width: 1px;" />
<uie:Toolbar name="TopToolbar" style="display: flex;">
<ui:Label text="Player" display-tooltip-when-elided="true" name="PlayerName" style="width: 200px; -unity-text-align: middle-left; padding-left: 5px;" />
<uie:ToolbarMenu display-tooltip-when-elided="true" name="ViewModeMenu" text="ViewMode" style="width: 100px; flex-grow: 0;" />
<uie:ToolbarSearchField focusable="true" name="SearchField" style="flex-grow: 1;" />
<uie:ToolbarButton text="刷新" display-tooltip-when-elided="true" name="SampleButton" style="width: 70px; background-color: rgb(15, 118, 31); -unity-text-align: middle-center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-left-width: 1px; border-right-width: 1px;" />
</uie:Toolbar>
<uie:Toolbar name="FrameToolbar">
<ui:SliderInt picking-mode="Ignore" label="Frame:" value="42" high-value="100" name="FrameSlider" style="flex-grow: 1;" />
<uie:ToolbarButton text=" &lt;&lt; " display-tooltip-when-elided="true" name="FrameLast" />
<uie:ToolbarButton text=" &gt;&gt; " display-tooltip-when-elided="true" name="FrameNext" />
<uie:ToolbarButton text="Clear" display-tooltip-when-elided="true" name="FrameClear" />
</uie:Toolbar>
</ui:UXML>

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace YooAsset.Editor
{
internal class RemotePlayerSession
{
private readonly List<DebugReport> _reportList = new List<DebugReport>();
/// <summary>
/// 用户ID
/// </summary>
public int PlayerId { private set; get; }
/// <summary>
/// 保存的报告最大数量
/// </summary>
public int MaxReportCount { private set; get; }
public int MinRangeValue
{
get
{
return 0;
}
}
public int MaxRangeValue
{
get
{
int index = _reportList.Count - 1;
if (index < 0)
index = 0;
return index;
}
}
public RemotePlayerSession(int playerId, int maxReportCount = 1000)
{
PlayerId = playerId;
MaxReportCount = maxReportCount;
}
/// <summary>
/// 清理缓存数据
/// </summary>
public void ClearDebugReport()
{
_reportList.Clear();
}
/// <summary>
/// 添加一个调试报告
/// </summary>
public void AddDebugReport(DebugReport report)
{
if (report == null)
Debug.LogWarning("Invalid debug report data !");
if (_reportList.Count >= MaxReportCount)
_reportList.RemoveAt(0);
_reportList.Add(report);
}
/// <summary>
/// 获取调试报告
/// </summary>
public DebugReport GetDebugReport(int rangeIndex)
{
if (_reportList.Count == 0)
return null;
if (rangeIndex < 0 || rangeIndex >= _reportList.Count)
return null;
return _reportList[rangeIndex];
}
/// <summary>
/// 规范索引值
/// </summary>
public int ClampRangeIndex(int rangeIndex)
{
if (rangeIndex < 0)
return 0;
if (rangeIndex > MaxRangeValue)
return MaxRangeValue;
return rangeIndex;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 89b4ea90b9f7e474d9e80077656ef6c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor
{
internal class AssetListDebuggerViewer
internal class DebuggerAssetListViewer
{
private VisualTreeAsset _visualAsset;
private TemplateContainer _root;
@@ -23,15 +23,11 @@ namespace YooAsset.Editor
/// </summary>
public void InitViewer()
{
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/VisualViewers/{nameof(AssetListDebuggerViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
// 加载布局文件
_visualAsset = EditorHelper.LoadWindowUXML<DebuggerAssetListViewer>();
if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetListDebuggerViewer)}.uxml : {uxml}");
return;
}
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
@@ -51,6 +47,18 @@ namespace YooAsset.Editor
_dependListView.bindItem = BindDependListViewItem;
}
/// <summary>
/// 清空页面
/// </summary>
public void ClearView()
{
_debugReport = null;
_assetListView.Clear();
_assetListView.ClearSelection();
_assetListView.itemsSource.Clear();
_assetListView.Rebuild();
}
/// <summary>
/// 填充页面数据
/// </summary>
@@ -58,7 +66,9 @@ namespace YooAsset.Editor
{
_debugReport = debugReport;
_assetListView.Clear();
_assetListView.ClearSelection();
_assetListView.itemsSource = FilterViewItems(debugReport, searchKeyWord);
_assetListView.Rebuild();
}
private List<DebugProviderInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord)
{
@@ -114,7 +124,7 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
label.style.width = 150;
element.Add(label);
}
@@ -124,6 +134,26 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
{
var label = new Label();
label.name = "Label4";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
element.Add(label);
}
{
var label = new Label();
label.name = "Label5";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 120;
element.Add(label);
}
@@ -139,19 +169,27 @@ namespace YooAsset.Editor
var label1 = element.Q<Label>("Label1");
label1.text = providerInfo.AssetPath;
// Ref Count
// Spawn Scene
var label2 = element.Q<Label>("Label2");
label2.text = providerInfo.RefCount.ToString();
label2.text = providerInfo.SpawnScene;
// Spawn Time
var label3 = element.Q<Label>("Label3");
label3.text = providerInfo.SpawnTime;
// Ref Count
var label4 = element.Q<Label>("Label4");
label4.text = providerInfo.RefCount.ToString();
// Status
StyleColor textColor;
if (providerInfo.Status == ProviderBase.EStatus.Fail)
if (providerInfo.Status == (int)ProviderBase.EStatus.Fail)
textColor = new StyleColor(Color.yellow);
else
textColor = label1.style.color;
var label3 = element.Q<Label>("Label3");
label3.text = providerInfo.Status.ToString();
label3.style.color = textColor;
var label5 = element.Q<Label>("Label5");
label5.text = providerInfo.Status.ToString();
label5.style.color = textColor;
}
private void AssetListView_onSelectionChange(IEnumerable<object> objs)
{
@@ -222,6 +260,7 @@ namespace YooAsset.Editor
_dependListView.Clear();
_dependListView.ClearSelection();
_dependListView.itemsSource = providerInfo.BundleInfos;
_dependListView.Rebuild();
}
}
}

View File

@@ -2,10 +2,12 @@
<ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Asset Path" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar2" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar3" style="width: 120px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Spawn Scene" display-tooltip-when-elided="true" name="TopBar2" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Spawn Time" display-tooltip-when-elided="true" name="TopBar3" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar4" style="width: 100px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar5" style="width: 120px; -unity-text-align: middle-left;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement>
<ui:VisualElement name="BottomGroup" style="height: 200px; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 1px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="BottomBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
@@ -13,6 +15,6 @@
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="BottomBar3" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="BottomBar4" style="width: 120px; -unity-text-align: middle-left;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="BottomListView" item-height="18" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="BottomListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement>
</ui:UXML>

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor
{
internal class BundleListDebuggerViewer
internal class DebuggerBundleListViewer
{
private VisualTreeAsset _visualAsset;
private TemplateContainer _root;
@@ -24,14 +24,10 @@ namespace YooAsset.Editor
public void InitViewer()
{
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/VisualViewers/{nameof(BundleListDebuggerViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
_visualAsset = EditorHelper.LoadWindowUXML<DebuggerBundleListViewer>();
if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(BundleListDebuggerViewer)}.uxml : {uxml}");
return;
}
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
@@ -39,17 +35,29 @@ namespace YooAsset.Editor
_bundleListView = _root.Q<ListView>("TopListView");
_bundleListView.makeItem = MakeAssetListViewItem;
_bundleListView.bindItem = BindAssetListViewItem;
#if UNITY_2020_1_OR_NEWER
_bundleListView.onSelectionChange += BundleListView_onSelectionChange;
#else
_bundleListView.onSelectionChanged += BundleListView_onSelectionChange;
#endif
// 使用列表
_usingListView = _root.Q<ListView>("BottomListView");
_usingListView.makeItem = MakeIncludeListViewItem;
_usingListView.bindItem = BindIncludeListViewItem;
}
/// <summary>
/// 清空页面
/// </summary>
public void ClearView()
{
_debugReport = null;
_bundleListView.Clear();
_bundleListView.ClearSelection();
_bundleListView.itemsSource.Clear();
_bundleListView.Rebuild();
}
/// <summary>
/// 填充页面数据
@@ -58,21 +66,23 @@ namespace YooAsset.Editor
{
_debugReport = debugReport;
_bundleListView.Clear();
_bundleListView.ClearSelection();
_bundleListView.itemsSource = FilterViewItems(debugReport, searchKeyWord);
_bundleListView.Rebuild();
}
private List<DebugBundleInfo> FilterViewItems(DebugReport debugReport, string searchKeyWord)
{
Dictionary<string, DebugBundleInfo> result = new Dictionary<string, DebugBundleInfo>(debugReport.ProviderInfos.Count);
foreach (var providerInfo in debugReport.ProviderInfos)
{
foreach(var bundleInfo in providerInfo.BundleInfos)
foreach (var bundleInfo in providerInfo.BundleInfos)
{
if (string.IsNullOrEmpty(searchKeyWord) == false)
{
if (bundleInfo.BundleName.Contains(searchKeyWord) == false)
continue;
}
if(result.ContainsKey(bundleInfo.BundleName) == false)
if (result.ContainsKey(bundleInfo.BundleName) == false)
result.Add(bundleInfo.BundleName, bundleInfo);
}
}
@@ -95,7 +105,7 @@ namespace YooAsset.Editor
_root.RemoveFromHierarchy();
}
// 顶部列表相关
private VisualElement MakeAssetListViewItem()
{
@@ -149,7 +159,7 @@ namespace YooAsset.Editor
// Status
StyleColor textColor;
if (bundleInfo.Status == AssetBundleLoaderBase.EStatus.Failed)
if (bundleInfo.Status == (int)AssetBundleLoaderBase.EStatus.Failed)
textColor = new StyleColor(Color.yellow);
else
textColor = label1.style.color;
@@ -188,7 +198,7 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
label.style.width = 150;
element.Add(label);
}
@@ -198,10 +208,30 @@ namespace YooAsset.Editor
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 150;
element.Add(label);
}
{
var label = new Label();
label.name = "Label4";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
element.Add(label);
}
{
var label = new Label();
label.name = "Label5";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 120;
element.Add(label);
}
return element;
}
private void BindIncludeListViewItem(VisualElement element, int index)
@@ -213,32 +243,41 @@ namespace YooAsset.Editor
var label1 = element.Q<Label>("Label1");
label1.text = providerInfo.AssetPath;
// Ref Count
// Spawn Scene
var label2 = element.Q<Label>("Label2");
label2.text = providerInfo.RefCount.ToString();
label2.text = providerInfo.SpawnScene;
// Spawn Time
var label3 = element.Q<Label>("Label3");
label3.text = providerInfo.SpawnTime;
// Ref Count
var label4 = element.Q<Label>("Label4");
label4.text = providerInfo.RefCount.ToString();
// Status
var label3 = element.Q<Label>("Label3");
label3.text = providerInfo.Status.ToString();
var label5 = element.Q<Label>("Label5");
label5.text = providerInfo.Status.ToString();
}
private void FillUsingListView(string bundleName)
{
_usingListView.Clear();
_usingListView.ClearSelection();
List<DebugProviderInfo> source = new List<DebugProviderInfo>();
foreach(var providerInfo in _debugReport.ProviderInfos)
{
List<DebugProviderInfo> source = new List<DebugProviderInfo>();
foreach (var providerInfo in _debugReport.ProviderInfos)
{
foreach(var bundleInfo in providerInfo.BundleInfos)
foreach (var bundleInfo in providerInfo.BundleInfos)
{
if (bundleInfo.BundleName == bundleName)
{
source.Add(providerInfo);
continue;
}
}
}
}
_usingListView.Clear();
_usingListView.ClearSelection();
_usingListView.itemsSource = source;
_usingListView.Rebuild();
}
}
}

View File

@@ -5,14 +5,16 @@
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="TopBar3" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="TopBar4" style="width: 120px; -unity-text-align: middle-left;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement>
<ui:VisualElement name="BottomGroup" style="height: 200px; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 1px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="BottomBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Using Assets" display-tooltip-when-elided="true" name="BottomBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="BottomBar3" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="BottomBar4" style="width: 120px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Spawn Scene" display-tooltip-when-elided="true" name="BottomBar2" style="width: 150px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Spawn Time" display-tooltip-when-elided="true" name="BottomBar3" style="width: 150px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Ref Count" display-tooltip-when-elided="true" name="BottomBar4" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="Status" display-tooltip-when-elided="true" name="BottomBar5" style="width: 120px; -unity-text-align: middle-left;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="BottomListView" item-height="18" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="BottomListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
</ui:VisualElement>
</ui:UXML>

View File

@@ -1,203 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleCollector
{
/// <summary>
/// 收集路径
/// 注意:支持文件夹或单个资源文件
/// </summary>
public string CollectPath = string.Empty;
/// <summary>
/// 打包规则类名
/// </summary>
public string PackRuleName = string.Empty;
/// <summary>
/// 过滤规则类名
/// </summary>
public string FilterRuleName = string.Empty;
/// <summary>
/// 不写入资源列表
/// </summary>
public bool NotWriteToAssetList = false;
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
if (AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(CollectPath) == null)
throw new Exception($"Invalid collect path : {CollectPath}");
if (AssetBundleGrouperSettingData.HasPackRuleName(PackRuleName) == false)
throw new Exception($"Invalid {nameof(IPackRule)} class type : {PackRuleName}");
if (AssetBundleGrouperSettingData.HasFilterRuleName(FilterRuleName) == false)
throw new Exception($"Invalid {nameof(IFilterRule)} class type : {FilterRuleName}");
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(AssetBundleGrouper grouper)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(1000);
bool isRawAsset = PackRuleName == nameof(PackRawFile);
// 如果是文件夹
if (AssetDatabase.IsValidFolder(CollectPath))
{
string collectDirectory = CollectPath;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
foreach (string assetPath in findAssets)
{
if (IsValidateAsset(assetPath) == false)
continue;
if (IsCollectAsset(assetPath) == false)
continue;
if (result.ContainsKey(assetPath) == false)
{
string bundleName = GetBundleName(grouper, assetPath, isRawAsset);
List<string> assetTags = GetAssetTags(grouper);
var collectAssetInfo = new CollectAssetInfo(bundleName, assetPath, assetTags, isRawAsset, NotWriteToAssetList);
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetPath} in collector : {CollectPath}");
}
}
}
else
{
string assetPath = CollectPath;
if (result.ContainsKey(assetPath) == false)
{
if (isRawAsset && NotWriteToAssetList)
UnityEngine.Debug.LogWarning($"Are you sure raw file are not write to asset list : {assetPath}");
string bundleName = GetBundleName(grouper, assetPath, isRawAsset);
List<string> assetTags = GetAssetTags(grouper);
var collectAssetInfo = new CollectAssetInfo(bundleName, assetPath, assetTags, isRawAsset, NotWriteToAssetList);
result.Add(assetPath, collectAssetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetPath} in collector : {CollectPath}");
}
}
// 返回列表
return result.Values.ToList();
}
private bool IsValidateAsset(string assetPath)
{
if (assetPath.StartsWith("Assets/") == false && assetPath.StartsWith("Packages/") == false)
return false;
if (AssetDatabase.IsValidFolder(assetPath))
return false;
// 注意:忽略编辑器下的类型资源
Type type = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (type == typeof(LightingDataAsset))
return false;
string ext = System.IO.Path.GetExtension(assetPath);
if (ext == "" || ext == ".dll" || ext == ".cs" || ext == ".js" || ext == ".boo" || ext == ".meta")
return false;
return true;
}
private bool IsCollectAsset(string assetPath)
{
// 如果收集全路径着色器
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders)
{
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
return true;
}
// 根据规则设置过滤资源文件
IFilterRule filterRuleInstance = AssetBundleGrouperSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
}
private string GetBundleName(AssetBundleGrouper grouper, string assetPath, bool isRawAsset)
{
// 如果收集全路径着色器
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders)
{
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader))
{
string bundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName;
return RevisedBundleName(bundleName, false);
}
}
// 根据规则设置获取资源包名称
{
IPackRule packRuleInstance = AssetBundleGrouperSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, grouper.GrouperName));
return RevisedBundleName(bundleName, isRawAsset);
}
}
private List<string> GetAssetTags(AssetBundleGrouper grouper)
{
List<string> tags = StringUtility.StringToStringList(grouper.AssetTags, ';');
List<string> temper = StringUtility.StringToStringList(AssetTags, ';');
tags.AddRange(temper);
return tags;
}
private List<string> GetAllDependencies(string mainAssetPath)
{
List<string> result = new List<string>();
string[] depends = AssetDatabase.GetDependencies(mainAssetPath, true);
foreach (string assetPath in depends)
{
if (IsValidateAsset(assetPath))
{
// 注意:排除主资源对象
if (assetPath != mainAssetPath)
result.Add(assetPath);
}
}
return result;
}
/// <summary>
/// 修正资源包名
/// </summary>
public static string RevisedBundleName(string bundleName, bool isRawBundle)
{
if (isRawBundle)
{
string fullName = $"{bundleName}.{YooAssetSettingsData.Setting.RawFileVariant}";
return EditorTools.GetRegularPath(fullName).ToLower();
}
else
{
string fullName = $"{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
return EditorTools.GetRegularPath(fullName).ToLower(); ;
}
}
}
}

View File

@@ -1,69 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleGrouper
{
/// <summary>
/// 分组名称
/// </summary>
public string GrouperName = string.Empty;
/// <summary>
/// 分组描述
/// </summary>
public string GrouperDesc = string.Empty;
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 分组的收集器列表
/// </summary>
public List<AssetBundleCollector> Collectors = new List<AssetBundleCollector>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
foreach(var collector in Collectors)
{
collector.CheckConfigError();
}
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets()
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
foreach(var collector in Collectors)
{
var temper = collector.GetAllCollectAssets(this);
foreach(var assetInfo in temper)
{
if(result.ContainsKey(assetInfo.AssetPath) == false)
{
result.Add(assetInfo.AssetPath, assetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in grouper : {GrouperName}");
}
}
}
return result.Values.ToList();
}
}
}

View File

@@ -1,162 +0,0 @@
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleGrouperConfig
{
public const string XmlShader = "Shader";
public const string XmlAutoCollectShader = "AutoCollectShader";
public const string XmlShaderBundleName = "ShaderBundleName";
public const string XmlGrouper = "Grouper";
public const string XmlGrouperName = "GrouperName";
public const string XmlGrouperDesc = "GrouperDesc";
public const string XmlCollector = "Collector";
public const string XmlDirectory = "CollectPath";
public const string XmlPackRule = "PackRule";
public const string XmlFilterRule = "FilterRule";
public const string XmlNotWriteToAssetList = "NotWriteToAssetList";
public const string XmlAssetTags = "AssetTags";
/// <summary>
/// 导入XML配置表
/// </summary>
public static void ImportXmlConfig(string filePath)
{
if (File.Exists(filePath) == false)
throw new FileNotFoundException(filePath);
if (Path.GetExtension(filePath) != ".xml")
throw new Exception($"Only support xml : {filePath}");
// 加载配置文件
XmlDocument xml = new XmlDocument();
xml.Load(filePath);
XmlElement root = xml.DocumentElement;
// 读取着色器配置
bool autoCollectShaders = false;
string shaderBundleName = string.Empty;
var shaderNodeList = root.GetElementsByTagName(XmlShader);
if (shaderNodeList.Count > 0)
{
XmlElement shaderElement = shaderNodeList[0] as XmlElement;
if (shaderElement.HasAttribute(XmlAutoCollectShader) == false)
throw new Exception($"Not found attribute {XmlAutoCollectShader} in {XmlShader}");
if (shaderElement.HasAttribute(XmlShaderBundleName) == false)
throw new Exception($"Not found attribute {XmlShaderBundleName} in {XmlShader}");
autoCollectShaders = shaderElement.GetAttribute(XmlAutoCollectShader) == "True" ? true : false;
shaderBundleName = shaderElement.GetAttribute(XmlShaderBundleName);
}
// 读取分组配置
List<AssetBundleGrouper> grouperTemper = new List<AssetBundleGrouper>();
var grouperNodeList = root.GetElementsByTagName(XmlGrouper);
foreach (var grouperNode in grouperNodeList)
{
XmlElement grouperElement = grouperNode as XmlElement;
if (grouperElement.HasAttribute(XmlGrouperName) == false)
throw new Exception($"Not found attribute {XmlGrouperName} in {XmlGrouper}");
if (grouperElement.HasAttribute(XmlGrouperDesc) == false)
throw new Exception($"Not found attribute {XmlGrouperDesc} in {XmlGrouper}");
if (grouperElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlGrouper}");
AssetBundleGrouper grouper = new AssetBundleGrouper();
grouper.GrouperName = grouperElement.GetAttribute(XmlGrouperName);
grouper.GrouperDesc = grouperElement.GetAttribute(XmlGrouperDesc);
grouper.AssetTags = grouperElement.GetAttribute(XmlAssetTags);
grouperTemper.Add(grouper);
// 读取收集器配置
var collectorNodeList = grouperElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlDirectory) == false)
throw new Exception($"Not found attribute {XmlDirectory} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlPackRule) == false)
throw new Exception($"Not found attribute {XmlPackRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlFilterRule) == false)
throw new Exception($"Not found attribute {XmlFilterRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlNotWriteToAssetList) == false)
throw new Exception($"Not found attribute {XmlNotWriteToAssetList} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlCollector}");
AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectorElement.GetAttribute(XmlDirectory);
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
collector.NotWriteToAssetList = collectorElement.GetAttribute(XmlNotWriteToAssetList) == "True" ? true : false;
collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags); ;
grouper.Collectors.Add(collector);
}
}
// 保存配置数据
AssetBundleGrouperSettingData.ClearAll();
AssetBundleGrouperSettingData.Setting.AutoCollectShaders = autoCollectShaders;
AssetBundleGrouperSettingData.Setting.ShadersBundleName = shaderBundleName;
AssetBundleGrouperSettingData.Setting.Groupers.AddRange(grouperTemper);
AssetBundleGrouperSettingData.SaveFile();
Debug.Log($"导入配置完毕!");
}
/// <summary>
/// 导出XML配置表
/// </summary>
public static void ExportXmlConfig(string savePath)
{
if (File.Exists(savePath))
File.Delete(savePath);
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<root>");
sb.AppendLine("</root>");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(sb.ToString());
XmlElement root = xmlDoc.DocumentElement;
// 设置着色器配置
var shaderElement = xmlDoc.CreateElement(XmlShader);
shaderElement.SetAttribute(XmlAutoCollectShader, AssetBundleGrouperSettingData.Setting.AutoCollectShaders.ToString());
shaderElement.SetAttribute(XmlShaderBundleName, AssetBundleGrouperSettingData.Setting.ShadersBundleName);
// 设置分组配置
foreach (var grouper in AssetBundleGrouperSettingData.Setting.Groupers)
{
var grouperElement = xmlDoc.CreateElement(XmlGrouper);
grouperElement.SetAttribute(XmlGrouperName, grouper.GrouperName);
grouperElement.SetAttribute(XmlGrouperDesc, grouper.GrouperDesc);
grouperElement.SetAttribute(XmlAssetTags, grouper.AssetTags);
root.AppendChild(grouperElement);
// 设置收集器配置
foreach (var collector in grouper.Collectors)
{
var collectorElement = xmlDoc.CreateElement(XmlCollector);
collectorElement.SetAttribute(XmlDirectory, collector.CollectPath);
collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName);
collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName);
collectorElement.SetAttribute(XmlNotWriteToAssetList, collector.NotWriteToAssetList.ToString());
collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags);
grouperElement.AppendChild(collectorElement);
}
}
// 生成配置文件
xmlDoc.Save(savePath);
Debug.Log($"导出配置完毕!");
}
}
}

View File

@@ -1,62 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleGrouperSetting : ScriptableObject
{
/// <summary>
/// 自动收集着色器
/// </summary>
public bool AutoCollectShaders = true;
/// <summary>
/// 自动收集的着色器资源包名称
/// </summary>
public string ShadersBundleName = "myshaders";
/// <summary>
/// 分组列表
/// </summary>
public List<AssetBundleGrouper> Groupers = new List<AssetBundleGrouper>();
/// <summary>
/// 检测配置错误
/// </summary>
public void CheckConfigError()
{
foreach (var grouper in Groupers)
{
grouper.CheckConfigError();
}
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets()
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
foreach (var grouper in Groupers)
{
var temper = grouper.GetAllCollectAssets();
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
{
result.Add(assetInfo.AssetPath, assetInfo);
}
else
{
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath}");
}
}
}
return result.Values.ToList();
}
}
}

View File

@@ -1,435 +0,0 @@
#if UNITY_2019_4_OR_NEWER
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace YooAsset.Editor
{
public class AssetBundleGrouperWindow : EditorWindow
{
[MenuItem("YooAsset/AssetBundle Grouper", false, 101)]
public static void ShowExample()
{
AssetBundleGrouperWindow window = GetWindow<AssetBundleGrouperWindow>();
window.titleContent = new GUIContent("资源包分组工具");
window.minSize = new Vector2(800, 600);
}
private List<string> _packRuleList;
private List<string> _filterRuleList;
private ListView _grouperListView;
private ListView _collectorListView;
private Toggle _autoCollectShaderToogle;
private TextField _shaderBundleNameTxt;
private TextField _grouperNameTxt;
private TextField _grouperDescTxt;
private TextField _grouperAssetTagsTxt;
private VisualElement _grouperContainer;
public void CreateGUI()
{
VisualElement root = this.rootVisualElement;
_packRuleList = AssetBundleGrouperSettingData.GetPackRuleNames();
_filterRuleList = AssetBundleGrouperSettingData.GetFilterRuleNames();
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleGrouper/{nameof(AssetBundleGrouperWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleGrouperWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
try
{
// 导入导出按钮
var exportBtn = root.Q<Button>("ExportButton");
exportBtn.clicked += ExportBtn_clicked;
var importBtn = root.Q<Button>("ImportButton");
importBtn.clicked += ImportBtn_clicked;
// 着色器相关
_autoCollectShaderToogle = root.Q<Toggle>("AutoCollectShader");
_autoCollectShaderToogle.RegisterValueChangedCallback(evt =>
{
AssetBundleGrouperSettingData.ModifyShader(evt.newValue, _shaderBundleNameTxt.value);
_shaderBundleNameTxt.SetEnabled(evt.newValue);
});
_shaderBundleNameTxt = root.Q<TextField>("ShaderBundleName");
_shaderBundleNameTxt.RegisterValueChangedCallback(evt =>
{
AssetBundleGrouperSettingData.ModifyShader(_autoCollectShaderToogle.value, evt.newValue);
});
// 分组列表相关
_grouperListView = root.Q<ListView>("GrouperListView");
_grouperListView.makeItem = MakeGrouperListViewItem;
_grouperListView.bindItem = BindGrouperListViewItem;
#if UNITY_2020_1_OR_NEWER
_grouperListView.onSelectionChange += GrouperListView_onSelectionChange;
#else
_grouperListView.onSelectionChanged += GrouperListView_onSelectionChange;
#endif
// 分组添加删除按钮
var grouperAddContainer = root.Q("GrouperAddContainer");
{
var addBtn = grouperAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddGrouperBtn_clicked;
var removeBtn = grouperAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemoveGrouperBtn_clicked;
}
// 分组容器
_grouperContainer = root.Q("GrouperContainer");
// 分组信息相关
_grouperNameTxt = root.Q<TextField>("GrouperName");
_grouperNameTxt.RegisterValueChangedCallback(evt =>
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper != null)
{
selectGrouper.GrouperName = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper);
}
});
_grouperDescTxt = root.Q<TextField>("GrouperDesc");
_grouperDescTxt.RegisterValueChangedCallback(evt =>
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper != null)
{
selectGrouper.GrouperDesc = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper);
}
});
_grouperAssetTagsTxt = root.Q<TextField>("GrouperAssetTags");
_grouperAssetTagsTxt.RegisterValueChangedCallback(evt =>
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper != null)
{
selectGrouper.AssetTags = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper);
}
});
// 收集列表相关
_collectorListView = root.Q<ListView>("CollectorListView");
_collectorListView.makeItem = MakeCollectorListViewItem;
_collectorListView.bindItem = BindCollectorListViewItem;
#if UNITY_2020_1_OR_NEWER
_collectorListView.onSelectionChange += CollectorListView_onSelectionChange;
#else
_collectorListView.onSelectionChanged += CollectorListView_onSelectionChange;
#endif
// 收集添加删除按钮
var collectorAddContainer = root.Q("CollectorAddContainer");
{
var addBtn = collectorAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddCollectorBtn_clicked;
var removeBtn = collectorAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemoveCollectorBtn_clicked;
}
// 刷新窗体
RefreshWindow();
}
catch (System.Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
if (AssetBundleGrouperSettingData.IsDirty)
AssetBundleGrouperSettingData.SaveFile();
}
// 刷新窗体
private void RefreshWindow()
{
_autoCollectShaderToogle.SetValueWithoutNotify(AssetBundleGrouperSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetEnabled(AssetBundleGrouperSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetValueWithoutNotify(AssetBundleGrouperSettingData.Setting.ShadersBundleName);
_grouperContainer.visible = false;
FillGrouperViewData();
}
// 导入导出按钮
private void ExportBtn_clicked()
{
string resultPath = EditorTools.OpenFolderPanel("Export XML", "Assets/");
if (resultPath != null)
{
AssetBundleGrouperConfig.ExportXmlConfig($"{resultPath}/{nameof(AssetBundleGrouperConfig)}.xml");
}
}
private void ImportBtn_clicked()
{
string resultPath = EditorTools.OpenFilePath("Import XML", "Assets/", "xml");
if (resultPath != null)
{
AssetBundleGrouperConfig.ImportXmlConfig(resultPath);
RefreshWindow();
}
}
// 分组列表相关
private void FillGrouperViewData()
{
_grouperListView.Clear();
_grouperListView.ClearSelection();
_grouperListView.itemsSource = AssetBundleGrouperSettingData.Setting.Groupers;
}
private VisualElement MakeGrouperListViewItem()
{
VisualElement element = new VisualElement();
{
var label = new Label();
label.name = "Label1";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.flexGrow = 1f;
label.style.height = 20f;
element.Add(label);
}
return element;
}
private void BindGrouperListViewItem(VisualElement element, int index)
{
var grouper = AssetBundleGrouperSettingData.Setting.Groupers[index];
// Grouper Name
var textField1 = element.Q<Label>("Label1");
if (string.IsNullOrEmpty(grouper.GrouperDesc))
textField1.text = grouper.GrouperName;
else
textField1.text = $"{grouper.GrouperName} ({grouper.GrouperDesc})";
}
private void GrouperListView_onSelectionChange(IEnumerable<object> objs)
{
FillCollectorViewData();
}
private void AddGrouperBtn_clicked()
{
AssetBundleGrouperSettingData.CreateGrouper("Default Grouper", string.Empty, string.Empty);
FillGrouperViewData();
}
private void RemoveGrouperBtn_clicked()
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper == null)
return;
AssetBundleGrouperSettingData.RemoveGrouper(selectGrouper);
FillGrouperViewData();
}
// 收集列表相关
private void FillCollectorViewData()
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper == null)
{
_grouperContainer.visible = false;
return;
}
_grouperContainer.visible = true;
_collectorListView.Clear();
_collectorListView.ClearSelection();
_collectorListView.itemsSource = selectGrouper.Collectors;
_grouperNameTxt.SetValueWithoutNotify(selectGrouper.GrouperName);
_grouperDescTxt.SetValueWithoutNotify(selectGrouper.GrouperDesc);
_grouperAssetTagsTxt.SetValueWithoutNotify(selectGrouper.AssetTags);
}
private VisualElement MakeCollectorListViewItem()
{
VisualElement element = new VisualElement();
VisualElement elementTop = new VisualElement();
elementTop.style.flexDirection = FlexDirection.Row;
element.Add(elementTop);
VisualElement elementBottom = new VisualElement();
elementBottom.style.flexDirection = FlexDirection.Row;
element.Add(elementBottom);
// Top VisualElement
{
var objectField = new ObjectField();
objectField.name = "ObjectField1";
objectField.label = "Collect Path";
objectField.objectType = typeof(UnityEngine.Object);
objectField.style.unityTextAlign = TextAnchor.MiddleLeft;
objectField.style.flexGrow = 1f;
elementTop.Add(objectField);
var label = objectField.Q<Label>();
label.style.minWidth = 80;
}
// Bottom VisualElement
{
var label = new Label();
label.style.width = 80;
elementBottom.Add(label);
}
{
var popupField = new PopupField<string>(_packRuleList, 0);
popupField.name = "PopupField1";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<string>(_filterRuleList, 0);
popupField.name = "PopupField2";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var toggle = new Toggle();
toggle.name = "Toggle1";
toggle.label = "NotWriteToAssetList";
toggle.style.unityTextAlign = TextAnchor.MiddleLeft;
toggle.style.width = 150;
toggle.style.marginLeft = 20;
elementBottom.Add(toggle);
var label = toggle.Q<Label>();
label.style.minWidth = 130;
}
{
var textField = new TextField();
textField.name = "TextField1";
textField.label = "Tags";
textField.style.width = 100;
textField.style.marginLeft = 20;
textField.style.flexGrow = 1;
elementBottom.Add(textField);
var label = textField.Q<Label>();
label.style.minWidth = 40;
}
return element;
}
private void BindCollectorListViewItem(VisualElement element, int index)
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper == null)
return;
var collector = selectGrouper.Collectors[index];
var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath);
if (collectObject != null)
collectObject.name = collector.CollectPath;
// Collect Path
var objectField1 = element.Q<ObjectField>("ObjectField1");
objectField1.SetValueWithoutNotify(collectObject);
objectField1.RegisterValueChangedCallback(evt =>
{
collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue);
objectField1.value.name = collector.CollectPath;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector);
});
// Pack Rule
var popupField1 = element.Q<PopupField<string>>("PopupField1");
popupField1.index = GetPackRuleIndex(collector.PackRuleName);
popupField1.RegisterValueChangedCallback(evt =>
{
collector.PackRuleName = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector);
});
// Filter Rule
var popupField2 = element.Q<PopupField<string>>("PopupField2");
popupField2.index = GetFilterRuleIndex(collector.FilterRuleName);
popupField2.RegisterValueChangedCallback(evt =>
{
collector.FilterRuleName = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector);
});
// NotWriteToAssetList
var toggle1 = element.Q<Toggle>("Toggle1");
toggle1.SetValueWithoutNotify(collector.NotWriteToAssetList);
toggle1.RegisterValueChangedCallback(evt =>
{
collector.NotWriteToAssetList = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector);
});
// Tags
var textFiled1 = element.Q<TextField>("TextField1");
textFiled1.SetValueWithoutNotify(collector.AssetTags);
textFiled1.RegisterValueChangedCallback(evt =>
{
collector.AssetTags = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector);
});
}
private void CollectorListView_onSelectionChange(IEnumerable<object> objs)
{
}
private void AddCollectorBtn_clicked()
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper == null)
return;
AssetBundleGrouperSettingData.CreateCollector(selectGrouper, string.Empty, nameof(PackDirectory), nameof(CollectAll), false);
FillCollectorViewData();
}
private void RemoveCollectorBtn_clicked()
{
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper;
if (selectGrouper == null)
return;
var selectCollector = _collectorListView.selectedItem as AssetBundleCollector;
if (selectCollector == null)
return;
AssetBundleGrouperSettingData.RemoveCollector(selectGrouper, selectCollector);
FillCollectorViewData();
}
private int GetPackRuleIndex(string packRuleName)
{
for (int i = 0; i < _packRuleList.Count; i++)
{
if (_packRuleList[i] == packRuleName)
return i;
}
return 0;
}
private int GetFilterRuleIndex(string filterRuleName)
{
for (int i = 0; i < _filterRuleList.Count; i++)
{
if (_filterRuleList[i] == filterRuleName)
return i;
}
return 0;
}
}
}
#endif

View File

@@ -0,0 +1,46 @@
using System.IO;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public class AssetBundleInspector
{
[CustomEditor(typeof(AssetBundle))]
internal class AssetBundleEditor : UnityEditor.Editor
{
internal bool pathFoldout = false;
internal bool advancedFoldout = false;
public override void OnInspectorGUI()
{
AssetBundle bundle = target as AssetBundle;
using (new EditorGUI.DisabledScope(true))
{
var leftStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
leftStyle.alignment = TextAnchor.UpperLeft;
GUILayout.Label(new GUIContent("Name: " + bundle.name), leftStyle);
var assetNames = bundle.GetAllAssetNames();
pathFoldout = EditorGUILayout.Foldout(pathFoldout, "Source Asset Paths");
if (pathFoldout)
{
EditorGUI.indentLevel++;
foreach (var asset in assetNames)
EditorGUILayout.LabelField(asset);
EditorGUI.indentLevel--;
}
advancedFoldout = EditorGUILayout.Foldout(advancedFoldout, "Advanced Data");
}
if (advancedFoldout)
{
EditorGUI.indentLevel++;
base.OnInspectorGUI();
EditorGUI.indentLevel--;
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b8016a4c13444bf45830d714ab2aa430
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace YooAsset.Editor
{
public static class AssetBundleRecorder
{
private static readonly Dictionary<string, AssetBundle> _loadedAssetBundles = new Dictionary<string, AssetBundle>(1000);
/// <summary>
/// 获取AssetBundle对象如果没有被缓存就重新加载。
/// </summary>
public static AssetBundle GetAssetBundle(string filePath)
{
// 如果文件不存在
if (File.Exists(filePath) == false)
{
Debug.LogWarning($"Not found asset bundle file : {filePath}");
return null;
}
// 验证文件有效性(可能文件被加密)
byte[] fileData = File.ReadAllBytes(filePath);
if (EditorTools.CheckBundleFileValid(fileData) == false)
{
Debug.LogWarning($"The asset bundle file is invalid and may be encrypted : {filePath}");
return null;
}
if (_loadedAssetBundles.TryGetValue(filePath, out AssetBundle bundle))
{
return bundle;
}
else
{
AssetBundle newBundle = AssetBundle.LoadFromFile(filePath);
if(newBundle != null)
{
string[] assetNames = newBundle.GetAllAssetNames();
foreach (string name in assetNames)
{
newBundle.LoadAsset(name);
}
_loadedAssetBundles.Add(filePath, newBundle);
}
return newBundle;
}
}
/// <summary>
/// 卸载所有已经加载的AssetBundle文件
/// </summary>
public static void UnloadAll()
{
foreach(var valuePair in _loadedAssetBundles)
{
if (valuePair.Value != null)
valuePair.Value.Unload(true);
}
_loadedAssetBundles.Clear();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9b2b5e436ee882d41bf53082bf7b23a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,4 +1,5 @@
#if UNITY_2019_4_OR_NEWER
using System;
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
@@ -11,8 +12,7 @@ namespace YooAsset.Editor
[MenuItem("YooAsset/AssetBundle Reporter", false, 103)]
public static void ShowExample()
{
AssetBundleReporterWindow window = GetWindow<AssetBundleReporterWindow>();
window.titleContent = new GUIContent("资源包报告工具");
AssetBundleReporterWindow window = GetWindow<AssetBundleReporterWindow>("资源包报告工具", true, EditorDefine.DockedWindowTypes);
window.minSize = new Vector2(800, 600);
}
@@ -38,60 +38,68 @@ namespace YooAsset.Editor
}
private ToolbarMenu _viewModeMenu;
private SummaryReporterViewer _summaryViewer;
private AssetListReporterViewer _assetListViewer;
private BundleListReporterViewer _bundleListViewer;
private ReporterSummaryViewer _summaryViewer;
private ReporterAssetListViewer _assetListViewer;
private ReporterBundleListViewer _bundleListViewer;
private EViewMode _viewMode;
private string _searchKeyWord;
private BuildReport _buildReport;
private string _reportFilePath;
private string _searchKeyWord;
public void CreateGUI()
{
VisualElement root = this.rootVisualElement;
// 加载布局文件
string rootPath = EditorTools.GetYooAssetPath();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/{nameof(AssetBundleReporterWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
try
{
Debug.LogError($"Not found {nameof(AssetBundleReporterWindow)}.uxml : {uxml}");
return;
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleReporterWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
// 导入按钮
var importBtn = root.Q<Button>("ImportButton");
importBtn.clicked += ImportBtn_onClick;
// 视图模式菜单
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
_viewModeMenu.menu.AppendAction(EViewMode.Summary.ToString(), ViewModeMenuAction0, ViewModeMenuFun0);
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), ViewModeMenuAction1, ViewModeMenuFun1);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), ViewModeMenuAction2, ViewModeMenuFun2);
// 搜索栏
var searchField = root.Q<ToolbarSearchField>("SearchField");
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
// 加载视图
_summaryViewer = new ReporterSummaryViewer();
_summaryViewer.InitViewer();
// 加载视图
_assetListViewer = new ReporterAssetListViewer();
_assetListViewer.InitViewer();
// 加载视图
_bundleListViewer = new ReporterBundleListViewer();
_bundleListViewer.InitViewer();
// 显示视图
_viewMode = EViewMode.Summary;
_viewModeMenu.text = EViewMode.Summary.ToString();
_summaryViewer.AttachParent(root);
}
visualAsset.CloneTree(root);
// 导入按钮
var importBtn = root.Q<Button>("ImportButton");
importBtn.clicked += ImportBtn_onClick;
// 视图模式菜单
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
_viewModeMenu.menu.AppendAction(EViewMode.Summary.ToString(), ViewModeMenuAction0, ViewModeMenuFun0);
_viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), ViewModeMenuAction1, ViewModeMenuFun1);
_viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), ViewModeMenuAction2, ViewModeMenuFun2);
// 搜索栏
var searchField = root.Q<ToolbarSearchField>("SearchField");
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
// 加载视图
_summaryViewer = new SummaryReporterViewer();
_summaryViewer.InitViewer();
// 加载视图
_assetListViewer = new AssetListReporterViewer();
_assetListViewer.InitViewer();
// 加载视图
_bundleListViewer = new BundleListReporterViewer();
_bundleListViewer.InitViewer();
// 显示视图
_viewMode = EViewMode.Summary;
_viewModeMenu.text = EViewMode.Summary.ToString();
_summaryViewer.AttachParent(root);
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
public void OnDestroy()
{
AssetBundleRecorder.UnloadAll();
}
private void ImportBtn_onClick()
@@ -100,19 +108,20 @@ namespace YooAsset.Editor
if (string.IsNullOrEmpty(selectFilePath))
return;
string jsonData = FileUtility.ReadFile(selectFilePath);
_reportFilePath = selectFilePath;
string jsonData = FileUtility.ReadFile(_reportFilePath);
_buildReport = BuildReport.Deserialize(jsonData);
_assetListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord);
_summaryViewer.FillViewData(_buildReport);
}
private void OnSearchKeyWordChange(ChangeEvent<string> e)
{
_searchKeyWord = e.newValue;
if(_buildReport != null)
if (_buildReport != null)
{
_assetListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord);
}
}
private void ViewModeMenuAction0(DropdownMenuAction action)

Some files were not shown because too many files have changed in this diff Show More