Compare commits

...

80 Commits
1.0.7 ... 1.1.0

Author SHA1 Message Date
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
173 changed files with 3811 additions and 1769 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 is not 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,7 @@
fileFormatVersion: 2
guid: 6375cc739b170490fbc6c38181b2c600
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -2,6 +2,169 @@
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.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 ## [1.0.7] - 2022-05-04
### Fixed ### Fixed

View File

@@ -30,8 +30,8 @@ namespace YooAsset.Editor
PipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(parameters.OutputRoot, parameters.BuildTarget); PipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(parameters.OutputRoot, parameters.BuildTarget);
if (parameters.BuildMode == EBuildMode.DryRunBuild) if (parameters.BuildMode == EBuildMode.DryRunBuild)
PipelineOutputDirectory += $"_{EBuildMode.DryRunBuild}"; PipelineOutputDirectory += $"_{EBuildMode.DryRunBuild}";
else if(parameters.BuildMode == EBuildMode.FastRunBuild) else if (parameters.BuildMode == EBuildMode.SimulateBuild)
PipelineOutputDirectory += $"_{EBuildMode.FastRunBuild}"; PipelineOutputDirectory += $"_{EBuildMode.SimulateBuild}";
} }
/// <summary> /// <summary>
@@ -53,10 +53,8 @@ namespace YooAsset.Editor
BuildAssetBundleOptions opt = BuildAssetBundleOptions.None; BuildAssetBundleOptions opt = BuildAssetBundleOptions.None;
opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it. opt |= BuildAssetBundleOptions.StrictMode; //Do not allow the build to succeed if any errors are reporting during it.
if (Parameters.BuildMode == EBuildMode.FastRunBuild) if (Parameters.BuildMode == EBuildMode.SimulateBuild)
{
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
}
if (Parameters.BuildMode == EBuildMode.DryRunBuild) if (Parameters.BuildMode == EBuildMode.DryRunBuild)
{ {
@@ -71,17 +69,13 @@ namespace YooAsset.Editor
if (Parameters.BuildMode == EBuildMode.ForceRebuild) if (Parameters.BuildMode == EBuildMode.ForceRebuild)
opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles opt |= BuildAssetBundleOptions.ForceRebuildAssetBundle; //Force rebuild the asset bundles
if (Parameters.AppendHash)
opt |= BuildAssetBundleOptions.AppendHashToAssetBundleName; //Append the hash to the assetBundle name
if (Parameters.DisableWriteTypeTree) if (Parameters.DisableWriteTypeTree)
opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree). opt |= BuildAssetBundleOptions.DisableWriteTypeTree; //Do not include type information within the asset bundle (don't write type tree).
if (Parameters.IgnoreTypeTreeChanges) if (Parameters.IgnoreTypeTreeChanges)
opt |= BuildAssetBundleOptions.IgnoreTypeTreeChanges; //Ignore the type tree changes when doing the incremental build check. 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.DisableLoadAssetByFileName; //Disables Asset Bundle LoadAsset by file name. opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
opt |= BuildAssetBundleOptions.DisableLoadAssetByFileNameWithExtension; //Disables Asset Bundle LoadAsset by file name with extension.
}
return opt; return opt;
} }
@@ -89,9 +83,9 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 获取构建的耗时(单位:秒) /// 获取构建的耗时(单位:秒)
/// </summary> /// </summary>
public int GetBuildingSeconds() public float GetBuildingSeconds()
{ {
int seconds = (int)(_buildWatch.ElapsedMilliseconds / 1000); float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return seconds; return seconds;
} }
public void BeginWatch() public void BeginWatch()
@@ -132,16 +126,16 @@ namespace YooAsset.Editor
new TaskCopyBuildinFiles(), //拷贝内置文件 new TaskCopyBuildinFiles(), //拷贝内置文件
}; };
if (buildParameters.BuildMode == EBuildMode.FastRunBuild) if (buildParameters.BuildMode == EBuildMode.SimulateBuild)
BuildRunner.EnableLog = false; BuildRunner.EnableLog = false;
else else
BuildRunner.EnableLog = true; BuildRunner.EnableLog = true;
bool succeed = BuildRunner.Run(pipeline, _buildContext); bool succeed = BuildRunner.Run(pipeline, _buildContext);
if (succeed) if (succeed)
Debug.Log($"{buildParameters.BuildMode}模式构建成功!"); Debug.Log($"{buildParameters.BuildMode} pipeline build succeed !");
else else
Debug.LogWarning($"{buildParameters.BuildMode}模式构建失败!"); Debug.LogWarning($"{buildParameters.BuildMode} pipeline build failed !");
return succeed; return succeed;
} }
} }

View File

@@ -16,7 +16,7 @@ namespace YooAsset.Editor
public EBuildMode BuildMode = EBuildMode.ForceRebuild; public EBuildMode BuildMode = EBuildMode.ForceRebuild;
/// <summary> /// <summary>
/// 内置资源标签 /// 内置资源标签(首包资源标签)
/// </summary> /// </summary>
public string BuildTags = string.Empty; public string BuildTags = string.Empty;

View File

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

View File

@@ -25,28 +25,24 @@ namespace YooAsset.Editor
private TextField _buildOutputField; private TextField _buildOutputField;
private IntegerField _buildVersionField; private IntegerField _buildVersionField;
private EnumField _buildModeField; private EnumField _buildModeField;
private TextField _buildTagsField; private TextField _buildinTagsField;
private PopupField<string> _encryptionField; private PopupField<string> _encryptionField;
private EnumField _compressionField; private EnumField _compressionField;
private Toggle _appendExtensionToggle; private Toggle _appendExtensionToggle;
public void CreateGUI() public void CreateGUI()
{ {
VisualElement root = this.rootVisualElement;
// 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath();
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 try
{ {
VisualElement root = this.rootVisualElement;
// 加载布局文件
var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleBuilderWindow>();
if (visualAsset == null)
return;
visualAsset.CloneTree(root);
_buildTarget = EditorUserBuildSettings.activeBuildTarget; _buildTarget = EditorUserBuildSettings.activeBuildTarget;
_encryptionServicesClassTypes = GetEncryptionServicesClassTypes(); _encryptionServicesClassTypes = GetEncryptionServicesClassTypes();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList(); _encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList();
@@ -78,11 +74,11 @@ namespace YooAsset.Editor
}); });
// 内置资源标签 // 内置资源标签
_buildTagsField = root.Q<TextField>("BuildinTags"); _buildinTagsField = root.Q<TextField>("BuildinTags");
_buildTagsField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildTags); _buildinTagsField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.BuildTags);
_buildTagsField.RegisterValueChangedCallback(evt => _buildinTagsField.RegisterValueChangedCallback(evt =>
{ {
AssetBundleBuilderSettingData.Setting.BuildTags = _buildTagsField.value; AssetBundleBuilderSettingData.Setting.BuildTags = _buildinTagsField.value;
}); });
// 加密方法 // 加密方法
@@ -111,7 +107,7 @@ namespace YooAsset.Editor
_compressionField = root.Q<EnumField>("Compression"); _compressionField = root.Q<EnumField>("Compression");
_compressionField.Init(AssetBundleBuilderSettingData.Setting.CompressOption); _compressionField.Init(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CompressOption); _compressionField.SetValueWithoutNotify(AssetBundleBuilderSettingData.Setting.CompressOption);
_compressionField.style.width = 300; _compressionField.style.width = 300;
_compressionField.RegisterValueChangedCallback(evt => _compressionField.RegisterValueChangedCallback(evt =>
{ {
AssetBundleBuilderSettingData.Setting.CompressOption = (ECompressOption)_compressionField.value; AssetBundleBuilderSettingData.Setting.CompressOption = (ECompressOption)_compressionField.value;
@@ -143,8 +139,9 @@ namespace YooAsset.Editor
private void RefreshWindow() private void RefreshWindow()
{ {
bool enableElement = AssetBundleBuilderSettingData.Setting.BuildMode == EBuildMode.ForceRebuild; var buildMode = AssetBundleBuilderSettingData.Setting.BuildMode;
_buildTagsField.SetEnabled(enableElement); bool enableElement = buildMode == EBuildMode.ForceRebuild;
_buildinTagsField.SetEnabled(enableElement);
_encryptionField.SetEnabled(enableElement); _encryptionField.SetEnabled(enableElement);
_compressionField.SetEnabled(enableElement); _compressionField.SetEnabled(enableElement);
_appendExtensionToggle.SetEnabled(enableElement); _appendExtensionToggle.SetEnabled(enableElement);
@@ -168,21 +165,28 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
private void ExecuteBuild() private void ExecuteBuild()
{ {
var buildMode = (EBuildMode)_buildModeField.value;
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters(); BuildParameters buildParameters = new BuildParameters();
buildParameters.OutputRoot = defaultOutputRoot; buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = _buildTarget; buildParameters.BuildTarget = _buildTarget;
buildParameters.BuildMode = (EBuildMode)_buildModeField.value; buildParameters.BuildMode = buildMode;
buildParameters.BuildVersion = _buildVersionField.value; buildParameters.BuildVersion = _buildVersionField.value;
buildParameters.BuildinTags = _buildTagsField.value; buildParameters.BuildinTags = _buildinTagsField.value;
buildParameters.VerifyBuildingResult = true; buildParameters.VerifyBuildingResult = true;
buildParameters.EnableAddressable = AssetBundleGrouperSettingData.Setting.EnableAddressable; buildParameters.EnableAddressable = AssetBundleCollectorSettingData.Setting.EnableAddressable;
buildParameters.AppendFileExtension = _appendExtensionToggle.value; buildParameters.AppendFileExtension = _appendExtensionToggle.value;
buildParameters.CopyBuildinTagFiles = buildMode == EBuildMode.ForceRebuild;
buildParameters.EncryptionServices = CreateEncryptionServicesInstance(); buildParameters.EncryptionServices = CreateEncryptionServicesInstance();
buildParameters.CompressOption = (ECompressOption)_compressionField.value; buildParameters.CompressOption = (ECompressOption)_compressionField.value;
AssetBundleBuilder builder = new AssetBundleBuilder(); AssetBundleBuilder builder = new AssetBundleBuilder();
builder.Run(buildParameters); bool succeed = builder.Run(buildParameters);
if (succeed)
{
EditorUtility.RevealInFinder($"{buildParameters.OutputRoot}/{buildParameters.BuildTarget}/{buildParameters.BuildVersion}");
}
} }
// 加密类相关 // 加密类相关
@@ -199,9 +203,7 @@ namespace YooAsset.Editor
} }
private List<Type> GetEncryptionServicesClassTypes() private List<Type> GetEncryptionServicesClassTypes()
{ {
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IEncryptionServices>(); return EditorTools.GetAssignableTypes(typeof(IEncryptionServices));
List<Type> classTypes = collection.ToList();
return classTypes;
} }
private IEncryptionServices CreateEncryptionServicesInstance() private IEncryptionServices CreateEncryptionServicesInstance()
{ {

View File

@@ -1,32 +1,30 @@
using System; using UnityEditor;
using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public static class AssetBundleRuntimeBuilder public static class AssetBundleSimulateBuilder
{ {
private static string _manifestFilePath = string.Empty; private static string _manifestFilePath = string.Empty;
/// <summary> /// <summary>
/// 快速模式构建 /// 模拟构建
/// </summary> /// </summary>
public static void FastBuild() public static void SimulateBuild()
{ {
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot(); string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();
BuildParameters buildParameters = new BuildParameters(); BuildParameters buildParameters = new BuildParameters();
buildParameters.OutputRoot = defaultOutputRoot; buildParameters.OutputRoot = defaultOutputRoot;
buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget; buildParameters.BuildTarget = EditorUserBuildSettings.activeBuildTarget;
buildParameters.BuildMode = EBuildMode.FastRunBuild; buildParameters.BuildMode = EBuildMode.SimulateBuild;
buildParameters.BuildVersion = AssetBundleBuilderSettingData.Setting.BuildVersion; buildParameters.BuildVersion = 999;
buildParameters.BuildinTags = AssetBundleBuilderSettingData.Setting.BuildTags; buildParameters.EnableAddressable = AssetBundleCollectorSettingData.Setting.EnableAddressable;
buildParameters.EnableAddressable = AssetBundleGrouperSettingData.Setting.EnableAddressable;
AssetBundleBuilder builder = new AssetBundleBuilder(); AssetBundleBuilder builder = new AssetBundleBuilder();
bool buildResult = builder.Run(buildParameters); bool buildResult = builder.Run(buildParameters);
if (buildResult) if (buildResult)
{ {
string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(buildParameters.OutputRoot, buildParameters.BuildTarget); string pipelineOutputDirectory = AssetBundleBuilderHelper.MakePipelineOutputDirectory(buildParameters.OutputRoot, buildParameters.BuildTarget);
_manifestFilePath = $"{pipelineOutputDirectory}_{EBuildMode.FastRunBuild}/{YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildVersion)}"; _manifestFilePath = $"{pipelineOutputDirectory}_{EBuildMode.SimulateBuild}/{YooAssetSettingsData.GetPatchManifestFileName(buildParameters.BuildVersion)}";
} }
else else
{ {
@@ -35,9 +33,9 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 获取构建的补丁清单文件路径 /// 获取构建的补丁清单路径
/// </summary> /// </summary>
public static string GetPatchManifestFilePath() public static string GetPatchManifestPath()
{ {
return _manifestFilePath; return _manifestFilePath;
} }

View File

@@ -9,6 +9,7 @@ namespace YooAsset.Editor
{ {
private string _mainBundleName; private string _mainBundleName;
private string _shareBundleName; private string _shareBundleName;
private bool _isAddAssetTags = false;
private readonly HashSet<string> _referenceBundleNames = new HashSet<string>(); private readonly HashSet<string> _referenceBundleNames = new HashSet<string>();
/// <summary> /// <summary>
@@ -37,10 +38,15 @@ namespace YooAsset.Editor
public bool IsShaderAsset { private set; get; } public bool IsShaderAsset { private set; get; }
/// <summary> /// <summary>
/// 资源分类标签列表 /// 资源分类标签
/// </summary> /// </summary>
public readonly List<string> AssetTags = new List<string>(); public readonly List<string> AssetTags = new List<string>();
/// <summary>
/// 资源包的分类标签
/// </summary>
public readonly List<string> BundleTags = new List<string>();
/// <summary> /// <summary>
/// 依赖的所有资源 /// 依赖的所有资源
/// 注意:包括零依赖资源和冗余资源(资源包名无效) /// 注意:包括零依赖资源和冗余资源(资源包名无效)
@@ -62,9 +68,9 @@ namespace YooAsset.Editor
else else
IsShaderAsset = false; IsShaderAsset = false;
} }
public BuildAssetInfo(ECollectorType collectorType, string assetPath) public BuildAssetInfo(string assetPath)
{ {
CollectorType = collectorType; CollectorType = ECollectorType.None;
Address = string.Empty; Address = string.Empty;
AssetPath = assetPath; AssetPath = assetPath;
IsRawAsset = false; IsRawAsset = false;
@@ -89,10 +95,15 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 添加资源分类标签 /// 添加资源分类标签
/// 说明:原始定义的资源分类标签
/// </summary> /// </summary>
public void AddAssetTags(List<string> tags) public void AddAssetTags(List<string> tags)
{ {
if (_isAddAssetTags)
throw new Exception("Should never get here !");
_isAddAssetTags = true;
foreach (var tag in tags) foreach (var tag in tags)
{ {
if (AssetTags.Contains(tag) == false) if (AssetTags.Contains(tag) == false)
@@ -101,6 +112,21 @@ namespace YooAsset.Editor
} }
} }
} }
/// <summary>
/// 添加资源包的分类标签
/// 说明:传染算法统计到的分类标签
/// </summary>
public void AddBundleTags(List<string> tags)
{
foreach (var tag in tags)
{
if (BundleTags.Contains(tag) == false)
{
BundleTags.Add(tag);
}
}
}
/// <summary> /// <summary>
/// 资源包名是否存在 /// 资源包名是否存在
@@ -147,11 +173,11 @@ namespace YooAsset.Editor
if (IsRawAsset) if (IsRawAsset)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders) if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{ {
if (IsShaderAsset) if (IsShaderAsset)
{ {
string shareBundleName = $"{AssetBundleGrouperSettingData.Setting.ShadersBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}"; string shareBundleName = $"{AssetBundleCollectorSettingData.Setting.ShadersBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower(); _shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower();
return; return;
} }
@@ -159,11 +185,9 @@ namespace YooAsset.Editor
if (_referenceBundleNames.Count > 1) if (_referenceBundleNames.Count > 1)
{ {
var bundleNameList = _referenceBundleNames.ToList(); IPackRule packRule = PackDirectory.StaticPackRule;
bundleNameList.Sort(); var bundleName = packRule.GetBundleName(new PackRuleData(AssetPath));
string combineName = string.Join("|", bundleNameList); var shareBundleName = $"share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
var combineNameHash = HashUtility.StringSHA1(combineName);
var shareBundleName = $"share_{combineNameHash}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower(); _shareBundleName = EditorTools.GetRegularPath(shareBundleName).ToLower();
} }
} }

View File

@@ -68,14 +68,14 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 获取资源标签列表 /// 获取资源包的分类标签列表
/// </summary> /// </summary>
public string[] GetAssetTags() public string[] GetBundleTags()
{ {
List<string> result = new List<string>(BuildinAssets.Count); List<string> result = new List<string>(BuildinAssets.Count);
foreach (var assetInfo in BuildinAssets) foreach (var assetInfo in BuildinAssets)
{ {
foreach (var assetTag in assetInfo.AssetTags) foreach (var assetTag in assetInfo.BundleTags)
{ {
if (result.Contains(assetTag) == false) if (result.Contains(assetTag) == false)
result.Add(assetTag); result.Add(assetTag);

View File

@@ -55,13 +55,13 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 获取AssetBundle内包含的标记列表 /// 获取资源包的分类标签列表
/// </summary> /// </summary>
public string[] GetAssetTags(string bundleName) public string[] GetBundleTags(string bundleName)
{ {
if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo)) if (TryGetBundleInfo(bundleName, out BuildBundleInfo bundleInfo))
{ {
return bundleInfo.GetAssetTags(); return bundleInfo.GetBundleTags();
} }
throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}"); throw new Exception($"Not found {nameof(BuildBundleInfo)} : {bundleName}");
} }

View File

@@ -10,16 +10,16 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 执行资源构建上下文 /// 执行资源构建上下文
/// </summary> /// </summary>
public static BuildMapContext CreateBuildMap() public static BuildMapContext CreateBuildMap(EBuildMode buildMode)
{ {
BuildMapContext context = new BuildMapContext(); BuildMapContext context = new BuildMapContext();
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>(1000); Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性 // 1. 检测配置合法性
AssetBundleGrouperSettingData.Setting.CheckConfigError(); AssetBundleCollectorSettingData.Setting.CheckConfigError();
// 2. 获取所有主动收集的资源 // 2. 获取所有收集器收集的资源
List<CollectAssetInfo> allCollectAssets = AssetBundleGrouperSettingData.Setting.GetAllCollectAssets(); List<CollectAssetInfo> allCollectAssets = AssetBundleCollectorSettingData.Setting.GetAllCollectAssets(buildMode);
// 3. 剔除未被引用的依赖资源 // 3. 剔除未被引用的依赖资源
List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>(); List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>();
@@ -36,13 +36,15 @@ namespace YooAsset.Editor
allCollectAssets.Remove(removeValue); allCollectAssets.Remove(removeValue);
} }
// 4. 录入主动收集的资源 // 4. 录入所有收集器收集的资源
foreach (var collectAssetInfo in allCollectAssets) foreach (var collectAssetInfo in allCollectAssets)
{ {
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false) if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{ {
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.CollectorType, collectAssetInfo.BundleName, collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset); var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags); buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo); buildAssetDic.Add(collectAssetInfo.AssetPath, buildAssetInfo);
} }
else else
@@ -58,13 +60,13 @@ namespace YooAsset.Editor
{ {
if (buildAssetDic.ContainsKey(dependAssetPath)) if (buildAssetDic.ContainsKey(dependAssetPath))
{ {
buildAssetDic[dependAssetPath].AddAssetTags(collectAssetInfo.AssetTags); buildAssetDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetInfo.BundleName); buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetInfo.BundleName);
} }
else else
{ {
var buildAssetInfo = new BuildAssetInfo(ECollectorType.None, dependAssetPath); var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags); buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetInfo.BundleName); buildAssetInfo.AddReferenceBundleName(collectAssetInfo.BundleName);
buildAssetDic.Add(dependAssetPath, buildAssetInfo); buildAssetDic.Add(dependAssetPath, buildAssetInfo);
} }
@@ -92,7 +94,7 @@ namespace YooAsset.Editor
pair.Value.CalculateFullBundleName(); pair.Value.CalculateFullBundleName();
} }
// 8. 移除参与构建的资源 // 8. 移除参与构建的资源
List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>(); List<BuildAssetInfo> removeBuildList = new List<BuildAssetInfo>();
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic) foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{ {

View File

@@ -30,7 +30,7 @@ namespace YooAsset.Editor
public int BuildVersion; public int BuildVersion;
/// <summary> /// <summary>
/// 内置资源的标记列表 /// 内置资源标签集合(首包资源标签)
/// 注意:分号为分隔符 /// 注意:分号为分隔符
/// </summary> /// </summary>
public string BuildinTags; public string BuildinTags;
@@ -46,17 +46,16 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool EnableAddressable = false; public bool EnableAddressable = false;
/// <summary>
/// 启用自动分包机制
/// 说明:自动分包机制可以实现资源零冗余
/// </summary>
public bool EnableAutoCollect = true;
/// <summary> /// <summary>
/// 追加文件扩展名 /// 追加文件扩展名
/// </summary> /// </summary>
public bool AppendFileExtension = false; public bool AppendFileExtension = false;
/// <summary>
/// 拷贝内置资源文件到StreamingAssets目录首包资源文件
/// </summary>
public bool CopyBuildinTagFiles = false;
/// <summary> /// <summary>
/// 加密类 /// 加密类
@@ -68,11 +67,6 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public ECompressOption CompressOption = ECompressOption.Uncompressed; public ECompressOption CompressOption = ECompressOption.Uncompressed;
/// <summary>
/// 文件名附加上哈希值
/// </summary>
public bool AppendHash = false;
/// <summary> /// <summary>
/// 禁止写入类型树结构(可以降低包体和内存并提高加载效率) /// 禁止写入类型树结构(可以降低包体和内存并提高加载效率)
/// </summary> /// </summary>
@@ -83,14 +77,9 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool IgnoreTypeTreeChanges = true; public bool IgnoreTypeTreeChanges = true;
/// <summary>
/// 禁用名称查找资源(可以降内存并提高加载效率)
/// </summary>
public bool DisableLoadAssetByFileName = false;
/// <summary> /// <summary>
/// 获取内置标记列表 /// 获取内置资源标签列表(首包资源标签)
/// </summary> /// </summary>
public List<string> GetBuildinTags() public List<string> GetBuildinTags()
{ {

View File

@@ -22,6 +22,11 @@ namespace YooAsset.Editor
/// 说明Meta文件记录的GUID /// 说明Meta文件记录的GUID
/// </summary> /// </summary>
public string AssetGUID; public string AssetGUID;
/// <summary>
/// 资源的分类标签
/// </summary>
public string[] AssetTags;
/// <summary> /// <summary>
/// 所属资源包名称 /// 所属资源包名称

View File

@@ -8,6 +8,21 @@ namespace YooAsset.Editor
[Serializable] [Serializable]
public class ReportBundleInfo 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>
/// 资源包名称 /// 资源包名称
/// </summary> /// </summary>
@@ -38,6 +53,26 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public int Flags; 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() public string GetTagsString()
{ {
if (Tags != null) if (Tags != null)
@@ -45,5 +80,16 @@ namespace YooAsset.Editor
else else
return string.Empty; return string.Empty;
} }
/// <summary>
/// 是否为原生文件
/// </summary>
public bool IsRawFile()
{
if (System.IO.Path.GetExtension(BundleName) == $".{YooAssetSettingsData.Setting.RawFileVariant}")
return true;
else
return false;
}
} }
} }

View File

@@ -48,16 +48,16 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public bool EnableAddressable; public bool EnableAddressable;
/// <summary>
/// 启用自动分包机制
/// </summary>
public bool EnableAutoCollect;
/// <summary> /// <summary>
/// 追加文件扩展名 /// 追加文件扩展名
/// </summary> /// </summary>
public bool AppendFileExtension; public bool AppendFileExtension;
/// <summary>
/// 拷贝内置资源文件
/// </summary>
public bool CopyBuildinTagFiles;
/// <summary> /// <summary>
/// 自动收集着色器 /// 自动收集着色器
/// </summary> /// </summary>
@@ -75,10 +75,8 @@ namespace YooAsset.Editor
// 构建参数 // 构建参数
public ECompressOption CompressOption; public ECompressOption CompressOption;
public bool AppendHash;
public bool DisableWriteTypeTree; public bool DisableWriteTypeTree;
public bool IgnoreTypeTreeChanges; public bool IgnoreTypeTreeChanges;
public bool DisableLoadAssetByFileName;
// 构建结果 // 构建结果
public int AssetFileTotalCount; public int AssetFileTotalCount;

View File

@@ -45,14 +45,22 @@ namespace YooAsset.Editor
} }
/// <summary> /// <summary>
/// 普通日志输出 /// 日志输出
/// </summary> /// </summary>
public static void Log(string info) public static void Log(string info)
{ {
if (EnableLog) if (EnableLog)
{ {
UnityEngine.Debug.Log(info); UnityEngine.Debug.Log(info);
} }
}
/// <summary>
/// 日志输出
/// </summary>
public static void Info(string info)
{
UnityEngine.Debug.Log(info);
} }
} }
} }

View File

@@ -21,9 +21,9 @@ namespace YooAsset.Editor
var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>(); var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); var buildMapContext = context.GetContextObject<BuildMapContext>();
// 快速构建模式下跳过引擎构建 // 模拟构建模式下跳过引擎构建
var buildMode = buildParametersContext.Parameters.BuildMode; var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.FastRunBuild) if (buildMode == EBuildMode.SimulateBuild)
return; return;
BuildAssetBundleOptions opt = buildParametersContext.GetPipelineBuildOptions(); BuildAssetBundleOptions opt = buildParametersContext.GetPipelineBuildOptions();

View File

@@ -13,7 +13,7 @@ namespace YooAsset.Editor
{ {
// 注意:我们只有在强制重建的时候才会拷贝 // 注意:我们只有在强制重建的时候才会拷贝
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
if (buildParameters.Parameters.BuildMode == EBuildMode.ForceRebuild) if (buildParameters.Parameters.CopyBuildinTagFiles)
{ {
// 清空流目录 // 清空流目录
AssetBundleBuilderHelper.ClearStreamingAssetsFolder(); AssetBundleBuilderHelper.ClearStreamingAssetsFolder();

View File

@@ -58,9 +58,7 @@ namespace YooAsset.Editor
{ {
List<PatchBundle> result = new List<PatchBundle>(1000); List<PatchBundle> result = new List<PatchBundle>(1000);
// 内置标记列表
List<string> buildinTags = buildParameters.Parameters.GetBuildinTags(); List<string> buildinTags = buildParameters.Parameters.GetBuildinTags();
var buildMode = buildParameters.Parameters.BuildMode; var buildMode = buildParameters.Parameters.BuildMode;
bool standardBuild = buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild; bool standardBuild = buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild;
foreach (var bundleInfo in buildMapContext.BundleInfos) foreach (var bundleInfo in buildMapContext.BundleInfos)
@@ -70,7 +68,7 @@ namespace YooAsset.Editor
string hash = GetFileHash(filePath, standardBuild); string hash = GetFileHash(filePath, standardBuild);
string crc32 = GetFileCRC(filePath, standardBuild); string crc32 = GetFileCRC(filePath, standardBuild);
long size = GetFileSize(filePath, standardBuild); long size = GetFileSize(filePath, standardBuild);
string[] tags = buildMapContext.GetAssetTags(bundleName); string[] tags = buildMapContext.GetBundleTags(bundleName);
bool isEncrypted = encryptionContext.IsEncryptFile(bundleName); bool isEncrypted = encryptionContext.IsEncryptFile(bundleName);
bool isBuildin = IsBuildinBundle(tags, buildinTags); bool isBuildin = IsBuildinBundle(tags, buildinTags);
bool isRawFile = bundleInfo.IsRawFile; bool isRawFile = bundleInfo.IsRawFile;
@@ -90,7 +88,7 @@ namespace YooAsset.Editor
} }
private bool IsBuildinBundle(string[] bundleTags, List<string> buildinTags) private bool IsBuildinBundle(string[] bundleTags, List<string> buildinTags)
{ {
// 注意:没有任何标记的Bundle文件默认为内置文件 // 注意:没有任何分类标签的Bundle文件默认为内置文件
if (bundleTags.Length == 0) if (bundleTags.Length == 0)
return true; return true;
@@ -141,6 +139,7 @@ namespace YooAsset.Editor
else else
patchAsset.Address = string.Empty; patchAsset.Address = string.Empty;
patchAsset.AssetPath = assetInfo.AssetPath; patchAsset.AssetPath = assetInfo.AssetPath;
patchAsset.AssetTags = assetInfo.AssetTags.ToArray();
patchAsset.BundleID = GetAssetBundleID(assetInfo.GetBundleName(), patchManifest); patchAsset.BundleID = GetAssetBundleID(assetInfo.GetBundleName(), patchManifest);
patchAsset.DependIDs = GetAssetBundleDependIDs(patchAsset.BundleID, assetInfo, patchManifest); patchAsset.DependIDs = GetAssetBundleDependIDs(patchAsset.BundleID, assetInfo, patchManifest);
result.Add(patchAsset); result.Add(patchAsset);

View File

@@ -12,38 +12,46 @@ namespace YooAsset.Editor
{ {
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>(); var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>(); 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(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{ {
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory, buildParameters.Parameters.BuildVersion); PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory, buildParameters.Parameters.BuildVersion);
BuildReport buildReport = new BuildReport(); BuildReport buildReport = new BuildReport();
buildParameters.StopWatch();
// 概述信息 // 概述信息
{ {
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion; buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildTime = DateTime.Now.ToString(); 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.BuildTarget = buildParameters.Parameters.BuildTarget;
buildReport.Summary.BuildMode = buildParameters.Parameters.BuildMode; buildReport.Summary.BuildMode = buildParameters.Parameters.BuildMode;
buildReport.Summary.BuildVersion = buildParameters.Parameters.BuildVersion; buildReport.Summary.BuildVersion = buildParameters.Parameters.BuildVersion;
buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags; buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags;
buildReport.Summary.EnableAddressable = buildParameters.Parameters.EnableAddressable; buildReport.Summary.EnableAddressable = buildParameters.Parameters.EnableAddressable;
buildReport.Summary.EnableAutoCollect = buildParameters.Parameters.EnableAutoCollect;
buildReport.Summary.AppendFileExtension = buildParameters.Parameters.AppendFileExtension; buildReport.Summary.AppendFileExtension = buildParameters.Parameters.AppendFileExtension;
buildReport.Summary.AutoCollectShaders = AssetBundleGrouperSettingData.Setting.AutoCollectShaders; buildReport.Summary.CopyBuildinTagFiles = buildParameters.Parameters.CopyBuildinTagFiles;
buildReport.Summary.ShadersBundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName; buildReport.Summary.AutoCollectShaders = AssetBundleCollectorSettingData.Setting.AutoCollectShaders;
buildReport.Summary.ShadersBundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.Parameters.EncryptionServices == null ? buildReport.Summary.EncryptionServicesClassName = buildParameters.Parameters.EncryptionServices == null ?
"null" : buildParameters.Parameters.EncryptionServices.GetType().FullName; "null" : buildParameters.Parameters.EncryptionServices.GetType().FullName;
// 构建参数 // 构建参数
buildReport.Summary.CompressOption = buildParameters.Parameters.CompressOption; buildReport.Summary.CompressOption = buildParameters.Parameters.CompressOption;
buildReport.Summary.AppendHash = buildParameters.Parameters.AppendHash;
buildReport.Summary.DisableWriteTypeTree = buildParameters.Parameters.DisableWriteTypeTree; buildReport.Summary.DisableWriteTypeTree = buildParameters.Parameters.DisableWriteTypeTree;
buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.Parameters.IgnoreTypeTreeChanges; buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.Parameters.IgnoreTypeTreeChanges;
buildReport.Summary.DisableLoadAssetByFileName = buildParameters.Parameters.DisableLoadAssetByFileName;
// 构建结果 // 构建结果
buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount; buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount;
@@ -65,6 +73,7 @@ namespace YooAsset.Editor
ReportAssetInfo reportAssetInfo = new ReportAssetInfo(); ReportAssetInfo reportAssetInfo = new ReportAssetInfo();
reportAssetInfo.Address = patchAsset.Address; reportAssetInfo.Address = patchAsset.Address;
reportAssetInfo.AssetPath = patchAsset.AssetPath; reportAssetInfo.AssetPath = patchAsset.AssetPath;
reportAssetInfo.AssetTags = patchAsset.AssetTags;
reportAssetInfo.AssetGUID = AssetDatabase.AssetPathToGUID(patchAsset.AssetPath); reportAssetInfo.AssetGUID = AssetDatabase.AssetPathToGUID(patchAsset.AssetPath);
reportAssetInfo.MainBundleName = mainBundle.BundleName; reportAssetInfo.MainBundleName = mainBundle.BundleName;
reportAssetInfo.MainBundleSize = mainBundle.SizeBytes; reportAssetInfo.MainBundleSize = mainBundle.SizeBytes;

View File

@@ -12,7 +12,8 @@ namespace YooAsset.Editor
{ {
void IBuildTask.Run(BuildContext context) void IBuildTask.Run(BuildContext context)
{ {
var buildMapContext = BuildMapCreater.CreateBuildMap(); var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode);
context.SetContextObject(buildMapContext); context.SetContextObject(buildMapContext);
BuildRunner.Log("构建内容准备完毕!"); BuildRunner.Log("构建内容准备完毕!");

View File

@@ -15,8 +15,8 @@ namespace YooAsset.Editor
{ {
var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>(); var buildParametersContext = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
// 快速构建模式下跳过验证 // 模拟构建模式下跳过验证
if (buildParametersContext.Parameters.BuildMode == EBuildMode.FastRunBuild) if (buildParametersContext.Parameters.BuildMode == EBuildMode.SimulateBuild)
return; return;
// 验证构建结果 // 验证构建结果

View File

@@ -16,14 +16,14 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
IncrementalBuild, IncrementalBuild,
/// <summary>
/// 快速构建模式
/// </summary>
FastRunBuild,
/// <summary> /// <summary>
/// 演练构建模式 /// 演练构建模式
/// </summary> /// </summary>
DryRunBuild, DryRunBuild,
/// <summary>
/// 模拟构建模式
/// </summary>
SimulateBuild,
} }
} }

View File

@@ -51,13 +51,13 @@ namespace YooAsset.Editor
if (CollectorType == ECollectorType.None) if (CollectorType == ECollectorType.None)
return false; return false;
if (AssetBundleGrouperSettingData.HasAddressRuleName(AddressRuleName) == false) if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
return false; return false;
if (AssetBundleGrouperSettingData.HasPackRuleName(PackRuleName) == false) if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
return false; return false;
if (AssetBundleGrouperSettingData.HasFilterRuleName(FilterRuleName) == false) if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
return false; return false;
return true; return true;
@@ -74,21 +74,28 @@ namespace YooAsset.Editor
if (CollectorType == ECollectorType.None) if (CollectorType == ECollectorType.None)
throw new Exception($"{nameof(ECollectorType)}.{ECollectorType.None} is invalid in collector : {CollectPath}"); throw new Exception($"{nameof(ECollectorType)}.{ECollectorType.None} is invalid in collector : {CollectPath}");
if (AssetBundleGrouperSettingData.HasPackRuleName(PackRuleName) == false) if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
throw new Exception($"Invalid {nameof(IPackRule)} class type : {PackRuleName} in collector : {CollectPath}"); throw new Exception($"Invalid {nameof(IPackRule)} class type : {PackRuleName} in collector : {CollectPath}");
if (AssetBundleGrouperSettingData.HasFilterRuleName(FilterRuleName) == false) if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
throw new Exception($"Invalid {nameof(IFilterRule)} class type : {FilterRuleName} in collector : {CollectPath}"); throw new Exception($"Invalid {nameof(IFilterRule)} class type : {FilterRuleName} in collector : {CollectPath}");
if (AssetBundleGrouperSettingData.HasAddressRuleName(AddressRuleName) == false) if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
throw new Exception($"Invalid {nameof(IAddressRule)} class type : {AddressRuleName} in collector : {CollectPath}"); throw new Exception($"Invalid {nameof(IAddressRule)} class type : {AddressRuleName} in collector : {CollectPath}");
} }
/// <summary> /// <summary>
/// 获取打包收集的资源文件 /// 获取打包收集的资源文件
/// </summary> /// </summary>
public List<CollectAssetInfo> GetAllCollectAssets(AssetBundleGrouper grouper) 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); Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(1000);
bool isRawAsset = PackRuleName == nameof(PackRawFile); bool isRawAsset = PackRuleName == nameof(PackRawFile);
@@ -97,7 +104,7 @@ namespace YooAsset.Editor
throw new Exception($"The raw file must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}"); throw new Exception($"The raw file must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}");
if (string.IsNullOrEmpty(CollectPath)) if (string.IsNullOrEmpty(CollectPath))
throw new Exception($"The collect path is null or empty in grouper : {grouper.GrouperName}"); throw new Exception($"The collect path is null or empty in group : {group.GroupName}");
// 收集打包资源 // 收集打包资源
if (AssetDatabase.IsValidFolder(CollectPath)) if (AssetDatabase.IsValidFolder(CollectPath))
@@ -110,7 +117,7 @@ namespace YooAsset.Editor
{ {
if (result.ContainsKey(assetPath) == false) if (result.ContainsKey(assetPath) == false)
{ {
var collectAssetInfo = CreateCollectAssetInfo(grouper, assetPath, isRawAsset); var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo); result.Add(assetPath, collectAssetInfo);
} }
else else
@@ -125,7 +132,7 @@ namespace YooAsset.Editor
string assetPath = CollectPath; string assetPath = CollectPath;
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath)) if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
{ {
var collectAssetInfo = CreateCollectAssetInfo(grouper, assetPath, isRawAsset); var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo); result.Add(assetPath, collectAssetInfo);
} }
else else
@@ -135,7 +142,7 @@ namespace YooAsset.Editor
} }
// 检测可寻址地址是否重复 // 检测可寻址地址是否重复
if (AssetBundleGrouperSettingData.Setting.EnableAddressable) if (AssetBundleCollectorSettingData.Setting.EnableAddressable)
{ {
HashSet<string> adressTemper = new HashSet<string>(); HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result) foreach (var collectInfoPair in result)
@@ -155,13 +162,19 @@ namespace YooAsset.Editor
return result.Values.ToList(); return result.Values.ToList();
} }
private CollectAssetInfo CreateCollectAssetInfo(AssetBundleGrouper grouper, string assetPath, bool isRawAsset) private CollectAssetInfo CreateCollectAssetInfo(EBuildMode buildMode, AssetBundleCollectorGroup group, string assetPath, bool isRawAsset)
{ {
string address = GetAddress(grouper, assetPath); string address = GetAddress(group, assetPath);
string bundleName = GetBundleName(grouper, assetPath); string bundleName = GetBundleName(group, assetPath);
List<string> assetTags = GetAssetTags(grouper); List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, assetTags, isRawAsset); CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, assetTags, isRawAsset);
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
// 注意:模拟构建模式下不需要收集依赖资源
if (buildMode == EBuildMode.SimulateBuild)
collectAssetInfo.DependAssets = new List<string>();
else
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
return collectAssetInfo; return collectAssetInfo;
} }
private bool IsValidateAsset(string assetPath) private bool IsValidateAsset(string assetPath)
@@ -186,7 +199,7 @@ namespace YooAsset.Editor
private bool IsCollectAsset(string assetPath) private bool IsCollectAsset(string assetPath)
{ {
// 如果收集全路径着色器 // 如果收集全路径着色器
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders) if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{ {
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath); Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader)) if (assetType == typeof(UnityEngine.Shader))
@@ -194,41 +207,41 @@ namespace YooAsset.Editor
} }
// 根据规则设置过滤资源文件 // 根据规则设置过滤资源文件
IFilterRule filterRuleInstance = AssetBundleGrouperSettingData.GetFilterRuleInstance(FilterRuleName); IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath)); return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
} }
private string GetAddress(AssetBundleGrouper grouper, string assetPath) private string GetAddress(AssetBundleCollectorGroup group, string assetPath)
{ {
if (CollectorType != ECollectorType.MainAssetCollector) if (CollectorType != ECollectorType.MainAssetCollector)
return string.Empty; return string.Empty;
IAddressRule addressRuleInstance = AssetBundleGrouperSettingData.GetAddressRuleInstance(AddressRuleName); IAddressRule addressRuleInstance = AssetBundleCollectorSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, grouper.GrouperName)); string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName));
return adressValue; return adressValue;
} }
private string GetBundleName(AssetBundleGrouper grouper, string assetPath) private string GetBundleName(AssetBundleCollectorGroup group, string assetPath)
{ {
// 如果自动收集所有的着色器 // 如果自动收集所有的着色器
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders) if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{ {
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath); System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader)) if (assetType == typeof(UnityEngine.Shader))
{ {
string bundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName; string bundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
return EditorTools.GetRegularPath(bundleName).ToLower(); return EditorTools.GetRegularPath(bundleName).ToLower();
} }
} }
// 根据规则设置获取资源包名称 // 根据规则设置获取资源包名称
{ {
IPackRule packRuleInstance = AssetBundleGrouperSettingData.GetPackRuleInstance(PackRuleName); IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, grouper.GrouperName)); string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName));
return EditorTools.GetRegularPath(bundleName).ToLower(); return EditorTools.GetRegularPath(bundleName).ToLower();
} }
} }
private List<string> GetAssetTags(AssetBundleGrouper grouper) private List<string> GetAssetTags(AssetBundleCollectorGroup group)
{ {
List<string> tags = StringUtility.StringToStringList(grouper.AssetTags, ';'); List<string> tags = StringUtility.StringToStringList(group.AssetTags, ';');
List<string> temper = StringUtility.StringToStringList(AssetTags, ';'); List<string> temper = StringUtility.StringToStringList(AssetTags, ';');
tags.AddRange(temper); tags.AddRange(temper);
return tags; return tags;

View File

@@ -8,14 +8,18 @@ using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class AssetBundleGrouperConfig public class AssetBundleCollectorConfig
{ {
public const string XmlShader = "Shader"; 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 XmlAutoCollectShader = "AutoCollectShader";
public const string XmlShaderBundleName = "ShaderBundleName"; public const string XmlShaderBundleName = "ShaderBundleName";
public const string XmlGrouper = "Grouper"; public const string XmlGroup = "Group";
public const string XmlGrouperName = "GrouperName"; public const string XmlGroupName = "GroupName";
public const string XmlGrouperDesc = "GrouperDesc"; public const string XmlGroupDesc = "GroupDesc";
public const string XmlCollector = "Collector"; public const string XmlCollector = "Collector";
public const string XmlCollectPath = "CollectPath"; public const string XmlCollectPath = "CollectPath";
public const string XmlCollectorType = "CollectType"; public const string XmlCollectorType = "CollectType";
@@ -40,43 +44,54 @@ namespace YooAsset.Editor
xml.Load(filePath); xml.Load(filePath);
XmlElement root = xml.DocumentElement; 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; bool autoCollectShaders = false;
string shaderBundleName = string.Empty; string shaderBundleName = string.Empty;
var shaderNodeList = root.GetElementsByTagName(XmlShader); var commonNodeList = root.GetElementsByTagName(XmlCommon);
if (shaderNodeList.Count > 0) if (commonNodeList.Count > 0)
{ {
XmlElement shaderElement = shaderNodeList[0] as XmlElement; XmlElement commonElement = commonNodeList[0] as XmlElement;
if (shaderElement.HasAttribute(XmlAutoCollectShader) == false) if (commonElement.HasAttribute(XmlEnableAddressable) == false)
throw new Exception($"Not found attribute {XmlAutoCollectShader} in {XmlShader}"); throw new Exception($"Not found attribute {XmlEnableAddressable} in {XmlCommon}");
if (shaderElement.HasAttribute(XmlShaderBundleName) == false) if (commonElement.HasAttribute(XmlAutoCollectShader) == false)
throw new Exception($"Not found attribute {XmlShaderBundleName} in {XmlShader}"); throw new Exception($"Not found attribute {XmlAutoCollectShader} in {XmlCommon}");
if (commonElement.HasAttribute(XmlShaderBundleName) == false)
throw new Exception($"Not found attribute {XmlShaderBundleName} in {XmlCommon}");
autoCollectShaders = shaderElement.GetAttribute(XmlAutoCollectShader) == "True" ? true : false; enableAddressable = commonElement.GetAttribute(XmlEnableAddressable) == "True" ? true : false;
shaderBundleName = shaderElement.GetAttribute(XmlShaderBundleName); autoCollectShaders = commonElement.GetAttribute(XmlAutoCollectShader) == "True" ? true : false;
shaderBundleName = commonElement.GetAttribute(XmlShaderBundleName);
} }
// 读取分组配置 // 读取分组配置
List<AssetBundleGrouper> grouperTemper = new List<AssetBundleGrouper>(); List<AssetBundleCollectorGroup> groupTemper = new List<AssetBundleCollectorGroup>();
var grouperNodeList = root.GetElementsByTagName(XmlGrouper); var groupNodeList = root.GetElementsByTagName(XmlGroup);
foreach (var grouperNode in grouperNodeList) foreach (var groupNode in groupNodeList)
{ {
XmlElement grouperElement = grouperNode as XmlElement; XmlElement groupElement = groupNode as XmlElement;
if (grouperElement.HasAttribute(XmlGrouperName) == false) if (groupElement.HasAttribute(XmlGroupName) == false)
throw new Exception($"Not found attribute {XmlGrouperName} in {XmlGrouper}"); throw new Exception($"Not found attribute {XmlGroupName} in {XmlGroup}");
if (grouperElement.HasAttribute(XmlGrouperDesc) == false) if (groupElement.HasAttribute(XmlGroupDesc) == false)
throw new Exception($"Not found attribute {XmlGrouperDesc} in {XmlGrouper}"); throw new Exception($"Not found attribute {XmlGroupDesc} in {XmlGroup}");
if (grouperElement.HasAttribute(XmlAssetTags) == false) if (groupElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlGrouper}"); throw new Exception($"Not found attribute {XmlAssetTags} in {XmlGroup}");
AssetBundleGrouper grouper = new AssetBundleGrouper(); AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
grouper.GrouperName = grouperElement.GetAttribute(XmlGrouperName); group.GroupName = groupElement.GetAttribute(XmlGroupName);
grouper.GrouperDesc = grouperElement.GetAttribute(XmlGrouperDesc); group.GroupDesc = groupElement.GetAttribute(XmlGroupDesc);
grouper.AssetTags = grouperElement.GetAttribute(XmlAssetTags); group.AssetTags = groupElement.GetAttribute(XmlAssetTags);
grouperTemper.Add(grouper); groupTemper.Add(group);
// 读取收集器配置 // 读取收集器配置
var collectorNodeList = grouperElement.GetElementsByTagName(XmlCollector); var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList) foreach (var collectorNode in collectorNodeList)
{ {
XmlElement collectorElement = collectorNode as XmlElement; XmlElement collectorElement = collectorNode as XmlElement;
@@ -100,16 +115,17 @@ namespace YooAsset.Editor
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule); collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule); collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags); ; collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags); ;
grouper.Collectors.Add(collector); group.Collectors.Add(collector);
} }
} }
// 保存配置数据 // 保存配置数据
AssetBundleGrouperSettingData.ClearAll(); AssetBundleCollectorSettingData.ClearAll();
AssetBundleGrouperSettingData.Setting.AutoCollectShaders = autoCollectShaders; AssetBundleCollectorSettingData.Setting.EnableAddressable = enableAddressable;
AssetBundleGrouperSettingData.Setting.ShadersBundleName = shaderBundleName; AssetBundleCollectorSettingData.Setting.AutoCollectShaders = autoCollectShaders;
AssetBundleGrouperSettingData.Setting.Groupers.AddRange(grouperTemper); AssetBundleCollectorSettingData.Setting.ShadersBundleName = shaderBundleName;
AssetBundleGrouperSettingData.SaveFile(); AssetBundleCollectorSettingData.Setting.Groups.AddRange(groupTemper);
AssetBundleCollectorSettingData.SaveFile();
Debug.Log($"导入配置完毕!"); Debug.Log($"导入配置完毕!");
} }
@@ -130,22 +146,27 @@ namespace YooAsset.Editor
xmlDoc.LoadXml(sb.ToString()); xmlDoc.LoadXml(sb.ToString());
XmlElement root = xmlDoc.DocumentElement; XmlElement root = xmlDoc.DocumentElement;
// 设置着色器配置 // 设置配置版本
var shaderElement = xmlDoc.CreateElement(XmlShader); root.SetAttribute(XmlVersion, ConfigVersion);
shaderElement.SetAttribute(XmlAutoCollectShader, AssetBundleGrouperSettingData.Setting.AutoCollectShaders.ToString());
shaderElement.SetAttribute(XmlShaderBundleName, AssetBundleGrouperSettingData.Setting.ShadersBundleName); // 设置公共配置
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 grouper in AssetBundleGrouperSettingData.Setting.Groupers) foreach (var group in AssetBundleCollectorSettingData.Setting.Groups)
{ {
var grouperElement = xmlDoc.CreateElement(XmlGrouper); var groupElement = xmlDoc.CreateElement(XmlGroup);
grouperElement.SetAttribute(XmlGrouperName, grouper.GrouperName); groupElement.SetAttribute(XmlGroupName, group.GroupName);
grouperElement.SetAttribute(XmlGrouperDesc, grouper.GrouperDesc); groupElement.SetAttribute(XmlGroupDesc, group.GroupDesc);
grouperElement.SetAttribute(XmlAssetTags, grouper.AssetTags); groupElement.SetAttribute(XmlAssetTags, group.AssetTags);
root.AppendChild(grouperElement); root.AppendChild(groupElement);
// 设置收集器配置 // 设置收集器配置
foreach (var collector in grouper.Collectors) foreach (var collector in group.Collectors)
{ {
var collectorElement = xmlDoc.CreateElement(XmlCollector); var collectorElement = xmlDoc.CreateElement(XmlCollector);
collectorElement.SetAttribute(XmlCollectPath, collector.CollectPath); collectorElement.SetAttribute(XmlCollectPath, collector.CollectPath);
@@ -154,7 +175,7 @@ namespace YooAsset.Editor
collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName); collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName);
collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName); collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName);
collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags); collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags);
grouperElement.AppendChild(collectorElement); groupElement.AppendChild(collectorElement);
} }
} }

View File

@@ -8,23 +8,28 @@ using UnityEditor;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
[Serializable] [Serializable]
public class AssetBundleGrouper public class AssetBundleCollectorGroup
{ {
/// <summary> /// <summary>
/// 分组名称 /// 分组名称
/// </summary> /// </summary>
public string GrouperName = string.Empty; public string GroupName = string.Empty;
/// <summary> /// <summary>
/// 分组描述 /// 分组描述
/// </summary> /// </summary>
public string GrouperDesc = string.Empty; public string GroupDesc = string.Empty;
/// <summary> /// <summary>
/// 资源分类标签 /// 资源分类标签
/// </summary> /// </summary>
public string AssetTags = string.Empty; public string AssetTags = string.Empty;
/// <summary>
/// 分组激活规则
/// </summary>
public string ActiveRuleName = nameof(EnableGroup);
/// <summary> /// <summary>
/// 分组的收集器列表 /// 分组的收集器列表
/// </summary> /// </summary>
@@ -36,6 +41,9 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public void CheckConfigError() 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) foreach (var collector in Collectors)
{ {
collector.CheckConfigError(); collector.CheckConfigError();
@@ -45,25 +53,32 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 获取打包收集的资源文件 /// 获取打包收集的资源文件
/// </summary> /// </summary>
public List<CollectAssetInfo> GetAllCollectAssets() public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{ {
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000); 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) foreach (var collector in Collectors)
{ {
var temper = collector.GetAllCollectAssets(this); var temper = collector.GetAllCollectAssets(buildMode, this);
foreach (var assetInfo in temper) foreach (var assetInfo in temper)
{ {
if (result.ContainsKey(assetInfo.AssetPath) == false) if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo); result.Add(assetInfo.AssetPath, assetInfo);
else else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in grouper : {GrouperName}"); throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in group : {GroupName}");
} }
} }
// 检测可寻址地址是否重复 // 检测可寻址地址是否重复
if (AssetBundleGrouperSettingData.Setting.EnableAddressable) if (AssetBundleCollectorSettingData.Setting.EnableAddressable)
{ {
HashSet<string> adressTemper = new HashSet<string>(); HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result) foreach (var collectInfoPair in result)
@@ -74,7 +89,7 @@ namespace YooAsset.Editor
if (adressTemper.Contains(address) == false) if (adressTemper.Contains(address) == false)
adressTemper.Add(address); adressTemper.Add(address);
else else
throw new Exception($"The address is existed : {address} in grouper : {GrouperName}"); throw new Exception($"The address is existed : {address} in group : {GroupName}");
} }
} }
} }

View File

@@ -6,7 +6,7 @@ using UnityEngine;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class AssetBundleGrouperSetting : ScriptableObject public class AssetBundleCollectorSetting : ScriptableObject
{ {
/// <summary> /// <summary>
/// 是否启用可寻址资源定位 /// 是否启用可寻址资源定位
@@ -26,7 +26,7 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 分组列表 /// 分组列表
/// </summary> /// </summary>
public List<AssetBundleGrouper> Groupers = new List<AssetBundleGrouper>(); public List<AssetBundleCollectorGroup> Groups = new List<AssetBundleCollectorGroup>();
/// <summary> /// <summary>
@@ -34,29 +34,29 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public void CheckConfigError() public void CheckConfigError()
{ {
foreach (var grouper in Groupers) foreach (var group in Groups)
{ {
grouper.CheckConfigError(); group.CheckConfigError();
} }
} }
/// <summary> /// <summary>
/// 获取打包收集的资源文件 /// 获取打包收集的资源文件
/// </summary> /// </summary>
public List<CollectAssetInfo> GetAllCollectAssets() public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{ {
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000); Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 收集打包资源 // 收集打包资源
foreach (var grouper in Groupers) foreach (var group in Groups)
{ {
var temper = grouper.GetAllCollectAssets(); var temper = group.GetAllCollectAssets(buildMode);
foreach (var assetInfo in temper) foreach (var assetInfo in temper)
{ {
if (result.ContainsKey(assetInfo.AssetPath) == false) if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo); result.Add(assetInfo.AssetPath, assetInfo);
else else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in grouper setting."); throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in group setting.");
} }
} }
@@ -72,7 +72,7 @@ namespace YooAsset.Editor
if (adressTemper.Contains(address) == false) if (adressTemper.Contains(address) == false)
adressTemper.Add(address); adressTemper.Add(address);
else else
throw new Exception($"The address is existed : {address} in grouper setting."); throw new Exception($"The address is existed : {address} in group setting.");
} }
} }
} }

View File

@@ -7,8 +7,11 @@ using UnityEditor;
namespace YooAsset.Editor 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, System.Type> _cacheAddressRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IAddressRule> _cacheAddressRuleInstance = new Dictionary<string, IAddressRule>(); private static readonly Dictionary<string, IAddressRule> _cacheAddressRuleInstance = new Dictionary<string, IAddressRule>();
@@ -24,8 +27,8 @@ namespace YooAsset.Editor
public static bool IsDirty { private set; get; } = false; public static bool IsDirty { private set; get; } = false;
private static AssetBundleGrouperSetting _setting = null; private static AssetBundleCollectorSetting _setting = null;
public static AssetBundleGrouperSetting Setting public static AssetBundleCollectorSetting Setting
{ {
get get
{ {
@@ -35,6 +38,18 @@ 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() public static List<string> GetAddressRuleNames()
{ {
if (_setting == null) if (_setting == null)
@@ -71,6 +86,15 @@ namespace YooAsset.Editor
} }
return names; 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) public static bool HasAddressRuleName(string ruleName)
{ {
foreach (var pair in _cacheAddressRuleTypes) foreach (var pair in _cacheAddressRuleTypes)
@@ -105,22 +129,7 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
private static void LoadSettingData() private static void LoadSettingData()
{ {
// 加载配置文件 _setting = EditorHelper.LoadSettingData<AssetBundleCollectorSetting>();
string settingFilePath = $"{EditorTools.GetYooAssetSettingPath()}/{nameof(AssetBundleGrouperSetting)}.asset";
_setting = AssetDatabase.LoadAssetAtPath<AssetBundleGrouperSetting>(settingFilePath);
if (_setting == null)
{
Debug.LogWarning($"Create new {nameof(AssetBundleGrouperSetting)}.asset : {settingFilePath}");
_setting = ScriptableObject.CreateInstance<AssetBundleGrouperSetting>();
EditorTools.CreateFileDirectory(settingFilePath);
AssetDatabase.CreateAsset(Setting, settingFilePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
else
{
Debug.Log($"Load {nameof(AssetBundleGrouperSetting)}.asset ok");
}
// IPackRule // IPackRule
{ {
@@ -135,12 +144,11 @@ namespace YooAsset.Editor
typeof(PackDirectory), typeof(PackDirectory),
typeof(PackTopDirectory), typeof(PackTopDirectory),
typeof(PackCollector), typeof(PackCollector),
typeof(PackGrouper), typeof(PackGroup),
typeof(PackRawFile), typeof(PackRawFile),
}; };
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IPackRule>(); var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule));
var customTypes = collection.ToList();
types.AddRange(customTypes); types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++) for (int i = 0; i < types.Count; i++)
{ {
@@ -165,8 +173,7 @@ namespace YooAsset.Editor
typeof(CollectSprite) typeof(CollectSprite)
}; };
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IFilterRule>(); var customTypes = EditorTools.GetAssignableTypes(typeof(IFilterRule));
var customTypes = collection.ToList();
types.AddRange(customTypes); types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++) for (int i = 0; i < types.Count; i++)
{ {
@@ -187,11 +194,10 @@ namespace YooAsset.Editor
{ {
typeof(AddressByFileName), typeof(AddressByFileName),
typeof(AddressByCollectorAndFileName), typeof(AddressByCollectorAndFileName),
typeof(AddressByGrouperAndFileName) typeof(AddressByGroupAndFileName)
}; };
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IAddressRule>(); var customTypes = EditorTools.GetAssignableTypes(typeof(IAddressRule));
var customTypes = collection.ToList();
types.AddRange(customTypes); types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++) for (int i = 0; i < types.Count; i++)
{ {
@@ -200,6 +206,29 @@ namespace YooAsset.Editor
_cacheAddressRuleTypes.Add(type.Name, type); _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> /// <summary>
@@ -212,7 +241,7 @@ namespace YooAsset.Editor
IsDirty = false; IsDirty = false;
EditorUtility.SetDirty(Setting); EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets(); AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetBundleGrouperSetting)}.asset is saved!"); Debug.Log($"{nameof(AssetBundleCollectorSetting)}.asset is saved!");
} }
} }
@@ -223,11 +252,28 @@ namespace YooAsset.Editor
{ {
Setting.AutoCollectShaders = false; Setting.AutoCollectShaders = false;
Setting.ShadersBundleName = string.Empty; Setting.ShadersBundleName = string.Empty;
Setting.Groupers.Clear(); Setting.Groups.Clear();
SaveFile(); 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) public static IAddressRule GetAddressRuleInstance(string ruleName)
{ {
if (_cacheAddressRuleInstance.TryGetValue(ruleName, out IAddressRule instance)) if (_cacheAddressRuleInstance.TryGetValue(ruleName, out IAddressRule instance))
@@ -296,43 +342,43 @@ namespace YooAsset.Editor
} }
// 资源分组编辑相关 // 资源分组编辑相关
public static void CreateGrouper(string grouperName) public static void CreateGroup(string groupName)
{ {
AssetBundleGrouper grouper = new AssetBundleGrouper(); AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
grouper.GrouperName = grouperName; group.GroupName = groupName;
Setting.Groupers.Add(grouper); Setting.Groups.Add(group);
IsDirty = true; 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; IsDirty = true;
} }
else 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; IsDirty = true;
} }
} }
// 资源收集器编辑相关 // 资源收集器编辑相关
public static void CreateCollector(AssetBundleGrouper grouper, string collectPath) public static void CreateCollector(AssetBundleCollectorGroup group, string collectPath)
{ {
AssetBundleCollector collector = new AssetBundleCollector(); AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectPath; collector.CollectPath = collectPath;
grouper.Collectors.Add(collector); group.Collectors.Add(collector);
IsDirty = true; 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; IsDirty = true;
} }
@@ -341,9 +387,9 @@ namespace YooAsset.Editor
Debug.LogWarning($"Failed remove collector : {collector.CollectPath}"); 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; IsDirty = true;
} }

View File

@@ -9,59 +9,60 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class AssetBundleGrouperWindow : EditorWindow public class AssetBundleCollectorWindow : EditorWindow
{ {
[MenuItem("YooAsset/AssetBundle Grouper", false, 101)] [MenuItem("YooAsset/AssetBundle Collector", false, 101)]
public static void ShowExample() public static void ShowExample()
{ {
AssetBundleGrouperWindow window = GetWindow<AssetBundleGrouperWindow>("资源包分组工具", true, EditorDefine.DockedWindowTypes); AssetBundleCollectorWindow window = GetWindow<AssetBundleCollectorWindow>("资源包收集工具", true, EditorDefine.DockedWindowTypes);
window.minSize = new Vector2(800, 600); window.minSize = new Vector2(800, 600);
} }
private List<string> _collectorTypeList; private List<string> _collectorTypeList;
private List<string> _activeRuleList;
private List<string> _addressRuleList; private List<string> _addressRuleList;
private List<string> _packRuleList; private List<string> _packRuleList;
private List<string> _filterRuleList; private List<string> _filterRuleList;
private ListView _grouperListView; private ListView _groupListView;
private ScrollView _collectorScrollView; private ScrollView _collectorScrollView;
private PopupField<string> _activeRulePopupField;
private Toggle _enableAddressableToogle; private Toggle _enableAddressableToogle;
private Toggle _autoCollectShaderToogle; private Toggle _autoCollectShaderToogle;
private TextField _shaderBundleNameTxt; private TextField _shaderBundleNameTxt;
private TextField _grouperNameTxt; private TextField _groupNameTxt;
private TextField _grouperDescTxt; private TextField _groupDescTxt;
private TextField _grouperAssetTagsTxt; private TextField _groupAssetTagsTxt;
private VisualElement _grouperContainer; private VisualElement _groupContainer;
private string _lastModifyGroup = string.Empty;
public void CreateGUI() public void CreateGUI()
{ {
Undo.undoRedoPerformed -= RefreshWindow; Undo.undoRedoPerformed -= RefreshWindow;
Undo.undoRedoPerformed += RefreshWindow; Undo.undoRedoPerformed += RefreshWindow;
VisualElement root = this.rootVisualElement;
_collectorTypeList = new List<string>()
{
$"{nameof(ECollectorType.MainAssetCollector)}",
$"{nameof(ECollectorType.StaticAssetCollector)}",
$"{nameof(ECollectorType.DependAssetCollector)}"
};
_addressRuleList = AssetBundleGrouperSettingData.GetAddressRuleNames();
_packRuleList = AssetBundleGrouperSettingData.GetPackRuleNames();
_filterRuleList = AssetBundleGrouperSettingData.GetFilterRuleNames();
// 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath();
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 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"); var exportBtn = root.Q<Button>("ExportButton");
exportBtn.clicked += ExportBtn_clicked; exportBtn.clicked += ExportBtn_clicked;
@@ -72,75 +73,76 @@ namespace YooAsset.Editor
_enableAddressableToogle = root.Q<Toggle>("EnableAddressable"); _enableAddressableToogle = root.Q<Toggle>("EnableAddressable");
_enableAddressableToogle.RegisterValueChangedCallback(evt => _enableAddressableToogle.RegisterValueChangedCallback(evt =>
{ {
AssetBundleGrouperSettingData.ModifyAddressable(evt.newValue); AssetBundleCollectorSettingData.ModifyAddressable(evt.newValue);
RefreshWindow();
}); });
_autoCollectShaderToogle = root.Q<Toggle>("AutoCollectShader"); _autoCollectShaderToogle = root.Q<Toggle>("AutoCollectShader");
_autoCollectShaderToogle.RegisterValueChangedCallback(evt => _autoCollectShaderToogle.RegisterValueChangedCallback(evt =>
{ {
AssetBundleGrouperSettingData.ModifyShader(evt.newValue, _shaderBundleNameTxt.value); AssetBundleCollectorSettingData.ModifyShader(evt.newValue, _shaderBundleNameTxt.value);
_shaderBundleNameTxt.SetEnabled(evt.newValue); _shaderBundleNameTxt.SetEnabled(evt.newValue);
}); });
_shaderBundleNameTxt = root.Q<TextField>("ShaderBundleName"); _shaderBundleNameTxt = root.Q<TextField>("ShaderBundleName");
_shaderBundleNameTxt.RegisterValueChangedCallback(evt => _shaderBundleNameTxt.RegisterValueChangedCallback(evt =>
{ {
AssetBundleGrouperSettingData.ModifyShader(_autoCollectShaderToogle.value, evt.newValue); AssetBundleCollectorSettingData.ModifyShader(_autoCollectShaderToogle.value, evt.newValue);
}); });
// 分组列表相关 // 分组列表相关
_grouperListView = root.Q<ListView>("GrouperListView"); _groupListView = root.Q<ListView>("GroupListView");
_grouperListView.makeItem = MakeGrouperListViewItem; _groupListView.makeItem = MakeGroupListViewItem;
_grouperListView.bindItem = BindGrouperListViewItem; _groupListView.bindItem = BindGroupListViewItem;
#if UNITY_2020_1_OR_NEWER #if UNITY_2020_1_OR_NEWER
_grouperListView.onSelectionChange += GrouperListView_onSelectionChange; _groupListView.onSelectionChange += GroupListView_onSelectionChange;
#else #else
_grouperListView.onSelectionChanged += GrouperListView_onSelectionChange; _groupListView.onSelectionChanged += GroupListView_onSelectionChange;
#endif #endif
// 分组添加删除按钮 // 分组添加删除按钮
var grouperAddContainer = root.Q("GrouperAddContainer"); var groupAddContainer = root.Q("GroupAddContainer");
{ {
var addBtn = grouperAddContainer.Q<Button>("AddBtn"); var addBtn = groupAddContainer.Q<Button>("AddBtn");
addBtn.clicked += AddGrouperBtn_clicked; addBtn.clicked += AddGroupBtn_clicked;
var removeBtn = grouperAddContainer.Q<Button>("RemoveBtn"); var removeBtn = groupAddContainer.Q<Button>("RemoveBtn");
removeBtn.clicked += RemoveGrouperBtn_clicked; removeBtn.clicked += RemoveGroupBtn_clicked;
} }
// 分组容器 // 分组容器
_grouperContainer = root.Q("GrouperContainer"); _groupContainer = root.Q("GroupContainer");
// 分组名称 // 分组名称
_grouperNameTxt = root.Q<TextField>("GrouperName"); _groupNameTxt = root.Q<TextField>("GroupName");
_grouperNameTxt.RegisterValueChangedCallback(evt => _groupNameTxt.RegisterValueChangedCallback(evt =>
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper != null) if (selectGroup != null)
{ {
selectGrouper.GrouperName = evt.newValue; selectGroup.GroupName = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper); AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
} }
}); });
// 分组备注 // 分组备注
_grouperDescTxt = root.Q<TextField>("GrouperDesc"); _groupDescTxt = root.Q<TextField>("GroupDesc");
_grouperDescTxt.RegisterValueChangedCallback(evt => _groupDescTxt.RegisterValueChangedCallback(evt =>
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper != null) if (selectGroup != null)
{ {
selectGrouper.GrouperDesc = evt.newValue; selectGroup.GroupDesc = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper); AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
} }
}); });
// 分组的资源标签 // 分组的资源标签
_grouperAssetTagsTxt = root.Q<TextField>("GrouperAssetTags"); _groupAssetTagsTxt = root.Q<TextField>("GroupAssetTags");
_grouperAssetTagsTxt.RegisterValueChangedCallback(evt => _groupAssetTagsTxt.RegisterValueChangedCallback(evt =>
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper != null) if (selectGroup != null)
{ {
selectGrouper.AssetTags = evt.newValue; selectGroup.AssetTags = evt.newValue;
AssetBundleGrouperSettingData.ModifyGrouper(selectGrouper); AssetBundleCollectorSettingData.ModifyGroup(selectGroup);
} }
}); });
@@ -156,6 +158,25 @@ namespace YooAsset.Editor
addBtn.clicked += AddCollectorBtn_clicked; 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(); RefreshWindow();
} }
@@ -166,26 +187,29 @@ namespace YooAsset.Editor
} }
public void OnDestroy() public void OnDestroy()
{ {
if (AssetBundleGrouperSettingData.IsDirty) // 注意:清空所有撤销操作
AssetBundleGrouperSettingData.SaveFile(); Undo.ClearAll();
if (AssetBundleCollectorSettingData.IsDirty)
AssetBundleCollectorSettingData.SaveFile();
} }
private void RefreshWindow() private void RefreshWindow()
{ {
_enableAddressableToogle.SetValueWithoutNotify(AssetBundleGrouperSettingData.Setting.EnableAddressable); _enableAddressableToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.EnableAddressable);
_autoCollectShaderToogle.SetValueWithoutNotify(AssetBundleGrouperSettingData.Setting.AutoCollectShaders); _autoCollectShaderToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetEnabled(AssetBundleGrouperSettingData.Setting.AutoCollectShaders); _shaderBundleNameTxt.SetEnabled(AssetBundleCollectorSettingData.Setting.AutoCollectShaders);
_shaderBundleNameTxt.SetValueWithoutNotify(AssetBundleGrouperSettingData.Setting.ShadersBundleName); _shaderBundleNameTxt.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShadersBundleName);
_grouperContainer.visible = false; _groupContainer.visible = false;
FillGrouperViewData(); FillGroupViewData();
} }
private void ExportBtn_clicked() private void ExportBtn_clicked()
{ {
string resultPath = EditorTools.OpenFolderPanel("Export XML", "Assets/"); string resultPath = EditorTools.OpenFolderPanel("Export XML", "Assets/");
if (resultPath != null) if (resultPath != null)
{ {
AssetBundleGrouperConfig.ExportXmlConfig($"{resultPath}/{nameof(AssetBundleGrouperConfig)}.xml"); AssetBundleCollectorConfig.ExportXmlConfig($"{resultPath}/{nameof(AssetBundleCollectorConfig)}.xml");
} }
} }
private void ImportBtn_clicked() private void ImportBtn_clicked()
@@ -193,20 +217,30 @@ namespace YooAsset.Editor
string resultPath = EditorTools.OpenFilePath("Import XML", "Assets/", "xml"); string resultPath = EditorTools.OpenFilePath("Import XML", "Assets/", "xml");
if (resultPath != null) if (resultPath != null)
{ {
AssetBundleGrouperConfig.ImportXmlConfig(resultPath); AssetBundleCollectorConfig.ImportXmlConfig(resultPath);
RefreshWindow(); RefreshWindow();
} }
} }
// 分组列表相关 // 分组列表相关
private void FillGrouperViewData() private void FillGroupViewData()
{ {
_grouperListView.Clear(); _groupListView.Clear();
_grouperListView.ClearSelection(); _groupListView.ClearSelection();
_grouperListView.itemsSource = AssetBundleGrouperSettingData.Setting.Groupers; _groupListView.itemsSource = AssetBundleCollectorSettingData.Setting.Groups;
_grouperListView.Rebuild(); _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 MakeGrouperListViewItem() private VisualElement MakeGroupListViewItem()
{ {
VisualElement element = new VisualElement(); VisualElement element = new VisualElement();
@@ -221,57 +255,63 @@ namespace YooAsset.Editor
return element; return element;
} }
private void BindGrouperListViewItem(VisualElement element, int index) private void BindGroupListViewItem(VisualElement element, int index)
{ {
var grouper = AssetBundleGrouperSettingData.Setting.Groupers[index]; var group = AssetBundleCollectorSettingData.Setting.Groups[index];
// Grouper Name // Group Name
var textField1 = element.Q<Label>("Label1"); var textField1 = element.Q<Label>("Label1");
if (string.IsNullOrEmpty(grouper.GrouperDesc)) if (string.IsNullOrEmpty(group.GroupDesc))
textField1.text = grouper.GrouperName; textField1.text = group.GroupName;
else else
textField1.text = $"{grouper.GrouperName} ({grouper.GrouperDesc})"; textField1.text = $"{group.GroupName} ({group.GroupDesc})";
// 激活状态
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(group.ActiveRuleName);
bool isActive = activeRule.IsActiveGroup();
textField1.SetEnabled(isActive);
} }
private void GrouperListView_onSelectionChange(IEnumerable<object> objs) private void GroupListView_onSelectionChange(IEnumerable<object> objs)
{ {
FillCollectorViewData(); FillCollectorViewData();
} }
private void AddGrouperBtn_clicked() private void AddGroupBtn_clicked()
{ {
Undo.RecordObject(AssetBundleGrouperSettingData.Setting, "YooAsset AddGrouper"); Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddGroup");
AssetBundleGrouperSettingData.CreateGrouper("Default Grouper"); AssetBundleCollectorSettingData.CreateGroup("Default Group");
FillGrouperViewData(); FillGroupViewData();
} }
private void RemoveGrouperBtn_clicked() private void RemoveGroupBtn_clicked()
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper == null) if (selectGroup == null)
return; return;
Undo.RecordObject(AssetBundleGrouperSettingData.Setting, "YooAsset RemoveGrouper"); Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveGroup");
AssetBundleCollectorSettingData.RemoveGroup(selectGroup);
AssetBundleGrouperSettingData.RemoveGrouper(selectGrouper); FillGroupViewData();
FillGrouperViewData();
} }
// 收集列表相关 // 收集列表相关
private void FillCollectorViewData() private void FillCollectorViewData()
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper == null) if (selectGroup == null)
{ {
_grouperContainer.visible = false; _groupContainer.visible = false;
return; return;
} }
_grouperContainer.visible = true; _lastModifyGroup = selectGroup.GroupName;
_grouperNameTxt.SetValueWithoutNotify(selectGrouper.GrouperName); _groupContainer.visible = true;
_grouperDescTxt.SetValueWithoutNotify(selectGrouper.GrouperDesc); _activeRulePopupField.SetValueWithoutNotify(selectGroup.ActiveRuleName);
_grouperAssetTagsTxt.SetValueWithoutNotify(selectGrouper.AssetTags); _groupNameTxt.SetValueWithoutNotify(selectGroup.GroupName);
_groupDescTxt.SetValueWithoutNotify(selectGroup.GroupDesc);
_groupAssetTagsTxt.SetValueWithoutNotify(selectGroup.AssetTags);
// 填充数据 // 填充数据
_collectorScrollView.Clear(); _collectorScrollView.Clear();
for (int i = 0; i < selectGrouper.Collectors.Count; i++) for (int i = 0; i < selectGroup.Collectors.Count; i++)
{ {
VisualElement element = MakeCollectorListViewItem(); VisualElement element = MakeCollectorListViewItem();
BindCollectorListViewItem(element, i); BindCollectorListViewItem(element, i);
@@ -391,18 +431,24 @@ namespace YooAsset.Editor
} }
private void BindCollectorListViewItem(VisualElement element, int index) private void BindCollectorListViewItem(VisualElement element, int index)
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper == null) if (selectGroup == null)
return; return;
var collector = selectGrouper.Collectors[index]; var collector = selectGroup.Collectors[index];
var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath); var collectObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(collector.CollectPath);
if (collectObject != null) if (collectObject != null)
collectObject.name = collector.CollectPath; collectObject.name = collector.CollectPath;
// Foldout // Foldout
var foldout = element.Q<Foldout>("Foldout1"); var foldout = element.Q<Foldout>("Foldout1");
RefreshFoldout(foldout, selectGrouper, collector); foldout.RegisterValueChangedCallback(evt =>
{
if (evt.newValue)
RefreshFoldout(foldout, selectGroup, collector);
else
foldout.Clear();
});
// Remove Button // Remove Button
var removeBtn = element.Q<Button>("Button1"); var removeBtn = element.Q<Button>("Button1");
@@ -418,8 +464,11 @@ namespace YooAsset.Editor
{ {
collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue); collector.CollectPath = AssetDatabase.GetAssetPath(evt.newValue);
objectField1.value.name = collector.CollectPath; objectField1.value.name = collector.CollectPath;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
RefreshFoldout(foldout, selectGrouper, collector); if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
}); });
// Collector Type // Collector Type
@@ -428,8 +477,11 @@ namespace YooAsset.Editor
popupField0.RegisterValueChangedCallback(evt => popupField0.RegisterValueChangedCallback(evt =>
{ {
collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(evt.newValue); collector.CollectorType = StringUtility.NameToEnum<ECollectorType>(evt.newValue);
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
RefreshFoldout(foldout, selectGrouper, collector); if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
}); });
// Address Rule // Address Rule
@@ -440,8 +492,11 @@ namespace YooAsset.Editor
popupField1.RegisterValueChangedCallback(evt => popupField1.RegisterValueChangedCallback(evt =>
{ {
collector.AddressRuleName = evt.newValue; collector.AddressRuleName = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
RefreshFoldout(foldout, selectGrouper, collector); if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
}); });
} }
@@ -451,8 +506,11 @@ namespace YooAsset.Editor
popupField2.RegisterValueChangedCallback(evt => popupField2.RegisterValueChangedCallback(evt =>
{ {
collector.PackRuleName = evt.newValue; collector.PackRuleName = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
RefreshFoldout(foldout, selectGrouper, collector); if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
}); });
// Filter Rule // Filter Rule
@@ -461,8 +519,11 @@ namespace YooAsset.Editor
popupField3.RegisterValueChangedCallback(evt => popupField3.RegisterValueChangedCallback(evt =>
{ {
collector.FilterRuleName = evt.newValue; collector.FilterRuleName = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
RefreshFoldout(foldout, selectGrouper, collector); if (foldout.value)
{
RefreshFoldout(foldout, selectGroup, collector);
}
}); });
// Tags // Tags
@@ -471,17 +532,17 @@ namespace YooAsset.Editor
textFiled1.RegisterValueChangedCallback(evt => textFiled1.RegisterValueChangedCallback(evt =>
{ {
collector.AssetTags = evt.newValue; collector.AssetTags = evt.newValue;
AssetBundleGrouperSettingData.ModifyCollector(selectGrouper, collector); AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
}); });
} }
private void RefreshFoldout(Foldout foldout, AssetBundleGrouper grouper, AssetBundleCollector collector) private void RefreshFoldout(Foldout foldout, AssetBundleCollectorGroup group, AssetBundleCollector collector)
{ {
// 清空旧元素 // 清空旧元素
foldout.Clear(); foldout.Clear();
if (collector.IsValid() == false) if (collector.IsValid() == false)
{ {
Debug.LogWarning($"The collector is invalid : {collector.CollectPath} in grouper : {grouper.GrouperName}"); Debug.LogWarning($"The collector is invalid : {collector.CollectPath} in group : {group.GroupName}");
return; return;
} }
@@ -491,7 +552,7 @@ namespace YooAsset.Editor
try try
{ {
collectAssetInfos = collector.GetAllCollectAssets(grouper); collectAssetInfos = collector.GetAllCollectAssets(EBuildMode.DryRunBuild, group);
} }
catch (System.Exception e) catch (System.Exception e)
{ {
@@ -509,8 +570,8 @@ namespace YooAsset.Editor
string showInfo = collectAssetInfo.AssetPath; string showInfo = collectAssetInfo.AssetPath;
if (_enableAddressableToogle.value) if (_enableAddressableToogle.value)
{ {
IAddressRule instance = AssetBundleGrouperSettingData.GetAddressRuleInstance(collector.AddressRuleName); IAddressRule instance = AssetBundleCollectorSettingData.GetAddressRuleInstance(collector.AddressRuleName);
AddressRuleData ruleData = new AddressRuleData(collectAssetInfo.AssetPath, collector.CollectPath, grouper.GrouperName); AddressRuleData ruleData = new AddressRuleData(collectAssetInfo.AssetPath, collector.CollectPath, group.GroupName);
string addressValue = instance.GetAssetAddress(ruleData); string addressValue = instance.GetAssetAddress(ruleData);
showInfo = $"[{addressValue}] {showInfo}"; showInfo = $"[{addressValue}] {showInfo}";
} }
@@ -527,21 +588,24 @@ namespace YooAsset.Editor
} }
private void AddCollectorBtn_clicked() private void AddCollectorBtn_clicked()
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper == null) if (selectGroup == null)
return; return;
AssetBundleGrouperSettingData.CreateCollector(selectGrouper, string.Empty); Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow AddCollector");
AssetBundleCollectorSettingData.CreateCollector(selectGroup, string.Empty);
FillCollectorViewData(); FillCollectorViewData();
} }
private void RemoveCollectorBtn_clicked(AssetBundleCollector selectCollector) private void RemoveCollectorBtn_clicked(AssetBundleCollector selectCollector)
{ {
var selectGrouper = _grouperListView.selectedItem as AssetBundleGrouper; var selectGroup = _groupListView.selectedItem as AssetBundleCollectorGroup;
if (selectGrouper == null) if (selectGroup == null)
return; return;
if (selectCollector == null) if (selectCollector == null)
return; return;
AssetBundleGrouperSettingData.RemoveCollector(selectGrouper, selectCollector);
Undo.RecordObject(AssetBundleCollectorSettingData.Setting, "YooAsset.AssetBundleCollectorWindow RemoveCollector");
AssetBundleCollectorSettingData.RemoveCollector(selectGroup, selectCollector);
FillCollectorViewData(); FillCollectorViewData();
} }

View File

@@ -5,8 +5,8 @@
</uie:Toolbar> </uie:Toolbar>
<ui:VisualElement name="ContentContainer" style="flex-grow: 1; flex-direction: row;"> <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: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" virtualization-method="DynamicHeight" style="flex-grow: 1;" /> <ui:ListView focusable="true" name="GroupListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="GrouperAddContainer" style="height: 20px; flex-direction: row; justify-content: center;"> <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="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" /> <ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement> </ui:VisualElement>
@@ -17,10 +17,11 @@
<ui:Toggle label="Auto Collect Shaders" name="AutoCollectShader" 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:TextField picking-mode="Ignore" label="Shader Bundle Name" name="ShaderBundleName" style="flex-grow: 1; -unity-text-align: middle-left;" />
</ui:VisualElement> </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:VisualElement name="GroupContainer" 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:VisualElement name="ActiveRuleContainer" style="height: 20px;" />
<ui:TextField picking-mode="Ignore" label="Grouper Desc" name="GrouperDesc" /> <ui:TextField picking-mode="Ignore" label="Group Name" name="GroupName" />
<ui:TextField picking-mode="Ignore" label="Grouper Asset Tags" name="GrouperAssetTags" /> <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:VisualElement name="CollectorAddContainer" style="height: 20px; flex-direction: row-reverse;">
<ui:Button text="[ + ]" display-tooltip-when-elided="true" name="AddBtn" /> <ui:Button text="[ + ]" display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement> </ui:VisualElement>

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

@@ -16,12 +16,12 @@ namespace YooAsset.Editor
/// <summary> /// <summary>
/// 以组名+文件名为定位地址 /// 以组名+文件名为定位地址
/// </summary> /// </summary>
public class AddressByGrouperAndFileName : IAddressRule public class AddressByGroupAndFileName : IAddressRule
{ {
string IAddressRule.GetAssetAddress(AddressRuleData data) string IAddressRule.GetAssetAddress(AddressRuleData data)
{ {
string fileName = Path.GetFileNameWithoutExtension(data.AssetPath); string fileName = Path.GetFileNameWithoutExtension(data.AssetPath);
return $"{data.GrouperName}_{fileName}"; return $"{data.GroupName}_{fileName}";
} }
} }

View File

@@ -44,10 +44,19 @@ namespace YooAsset.Editor
{ {
public bool IsCollectAsset(FilterRuleData data) public bool IsCollectAsset(FilterRuleData data)
{ {
if (AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath) == typeof(Sprite)) var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
return true; 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 else
{
return false; return false;
}
} }
} }
} }

View File

@@ -28,6 +28,8 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public class PackDirectory : IPackRule public class PackDirectory : IPackRule
{ {
public static PackDirectory StaticPackRule = new PackDirectory();
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
{ {
return Path.GetDirectoryName(data.AssetPath); return Path.GetDirectoryName(data.AssetPath);
@@ -78,11 +80,11 @@ namespace YooAsset.Editor
/// 以分组名称作为资源包名 /// 以分组名称作为资源包名
/// 注意:收集的所有文件打进一个资源包 /// 注意:收集的所有文件打进一个资源包
/// </summary> /// </summary>
public class PackGrouper : IPackRule public class PackGroup : IPackRule
{ {
string IPackRule.GetBundleName(PackRuleData data) string IPackRule.GetBundleName(PackRuleData data)
{ {
return data.GrouperName; return data.GroupName;
} }
} }

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

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

View File

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

View File

@@ -1,140 +1,205 @@
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
using System;
using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
using UnityEditor.UIElements; using UnityEditor.UIElements;
using UnityEditor.Networking.PlayerConnection;
using UnityEngine.Networking.PlayerConnection;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
public class AssetBundleDebuggerWindow : EditorWindow public class AssetBundleDebuggerWindow : EditorWindow
{ {
[MenuItem("YooAsset/AssetBundle Debugger", false, 104)] [MenuItem("YooAsset/AssetBundle Debugger", false, 104)]
public static void ShowExample() public static void ShowExample()
{ {
AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>("资源包调试工具", true, EditorDefine.DockedWindowTypes); AssetBundleDebuggerWindow wnd = GetWindow<AssetBundleDebuggerWindow>("资源包调试工具", true, EditorDefine.DockedWindowTypes);
wnd.minSize = new Vector2(800, 600); wnd.minSize = new Vector2(800, 600);
} }
/// <summary> /// <summary>
/// 视图模式 /// 视图模式
/// </summary> /// </summary>
private enum EViewMode private enum EViewMode
{ {
/// <summary> /// <summary>
/// 内存视图 /// 内存视图
/// </summary> /// </summary>
MemoryView, MemoryView,
/// <summary> /// <summary>
/// 资源对象视图 /// 资源对象视图
/// </summary> /// </summary>
AssetView, AssetView,
/// <summary> /// <summary>
/// 资源包视图 /// 资源包视图
/// </summary> /// </summary>
BundleView, BundleView,
} }
private ToolbarMenu _viewModeMenu;
private AssetListDebuggerViewer _assetListViewer;
private BundleListDebuggerViewer _bundleListViewer;
private EViewMode _viewMode;
private readonly DebugReport _debugReport = new DebugReport();
private string _searchKeyWord;
public void CreateGUI() private readonly Dictionary<int, RemotePlayerSession> _playerSessions = new Dictionary<int, RemotePlayerSession>();
{
VisualElement root = rootVisualElement;
// 加载布局文件 private Label _playerName;
string rootPath = EditorTools.GetYooAssetSourcePath(); private ToolbarMenu _viewModeMenu;
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/{nameof(AssetBundleDebuggerWindow)}.uxml"; private DebuggerAssetListViewer _assetListViewer;
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml); private DebuggerBundleListViewer _bundleListViewer;
if (visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetBundleDebuggerWindow)}.uxml : {uxml}");
return;
}
visualAsset.CloneTree(root);
// 采样按钮 private EViewMode _viewMode;
var sampleBtn = root.Q<Button>("SampleButton"); private DebugReport _debugReport;
sampleBtn.clicked += SampleBtn_onClick; private string _searchKeyWord;
// 视口模式菜单
_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);
// 搜索栏 public void CreateGUI()
var searchField = root.Q<ToolbarSearchField>("SearchField"); {
searchField.RegisterValueChangedCallback(OnSearchKeyWordChange); try
{
VisualElement root = rootVisualElement;
// 加载视图 // 加载布局文件
_assetListViewer = new AssetListDebuggerViewer(); var visualAsset = EditorHelper.LoadWindowUXML<AssetBundleDebuggerWindow>();
_assetListViewer.InitViewer(); if (visualAsset == null)
return;
// 加载视图 visualAsset.CloneTree(root);
_bundleListViewer = new BundleListDebuggerViewer();
_bundleListViewer.InitViewer();
// 显示视图 // 采样按钮
_viewMode = EViewMode.AssetView; var sampleBtn = root.Q<Button>("SampleButton");
_viewModeMenu.text = EViewMode.AssetView.ToString(); sampleBtn.clicked += SampleBtn_onClick;
_assetListViewer.AttachParent(root);
} // 用户列表菜单
private void SampleBtn_onClick() _playerName = root.Q<Label>("PlayerName");
{ _playerName.text = "Editor player";
YooAssets.GetDebugReport(_debugReport);
_assetListViewer.FillViewData(_debugReport, _searchKeyWord); // 视口模式菜单
_bundleListViewer.FillViewData(_debugReport, _searchKeyWord); _viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu");
} _viewModeMenu.menu.AppendAction(EViewMode.AssetView.ToString(), ViewModeMenuAction, ViewModeMenuFun, EViewMode.AssetView);
private void OnSearchKeyWordChange(ChangeEvent<string> e) _viewModeMenu.menu.AppendAction(EViewMode.BundleView.ToString(), ViewModeMenuAction, ViewModeMenuFun, EViewMode.BundleView);
{ _viewModeMenu.text = EViewMode.AssetView.ToString();
_searchKeyWord = e.newValue;
_assetListViewer.FillViewData(_debugReport, _searchKeyWord); // 搜索栏
_bundleListViewer.FillViewData(_debugReport, _searchKeyWord); var searchField = root.Q<ToolbarSearchField>("SearchField");
} searchField.RegisterValueChangedCallback(OnSearchKeyWordChange);
private void ViewModeMenuAction1(DropdownMenuAction action)
{ // 加载视图
if (_viewMode != EViewMode.AssetView) _assetListViewer = new DebuggerAssetListViewer();
{ _assetListViewer.InitViewer();
_viewMode = EViewMode.AssetView;
VisualElement root = this.rootVisualElement; // 加载视图
_viewModeMenu.text = EViewMode.AssetView.ToString(); _bundleListViewer = new DebuggerBundleListViewer();
_assetListViewer.AttachParent(root); _bundleListViewer.InitViewer();
_bundleListViewer.DetachParent();
} // 显示视图
} _viewMode = EViewMode.AssetView;
private void ViewModeMenuAction2(DropdownMenuAction action) _assetListViewer.AttachParent(root);
{
if (_viewMode != EViewMode.BundleView) // 远程调试
{ EditorConnection.instance.Initialize();
_viewMode = EViewMode.BundleView; EditorConnection.instance.RegisterConnection(OnHandleConnectionEvent);
VisualElement root = this.rootVisualElement; EditorConnection.instance.RegisterDisconnection(OnHandleDisconnectionEvent);
_viewModeMenu.text = EViewMode.BundleView.ToString(); EditorConnection.instance.Register(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
_assetListViewer.DetachParent(); RemoteDebuggerInRuntime.EditorHandleDebugReportCallback = OnHandleDebugReport;
_bundleListViewer.AttachParent(root); }
} catch (Exception e)
} {
private DropdownMenuAction.Status ViewModeMenuFun1(DropdownMenuAction action) Debug.LogError(e.ToString());
{ }
if (_viewMode == EViewMode.AssetView) }
return DropdownMenuAction.Status.Checked; public void OnDestroy()
else {
return DropdownMenuAction.Status.Normal; // 远程调试
} EditorConnection.instance.UnregisterConnection(OnHandleConnectionEvent);
private DropdownMenuAction.Status ViewModeMenuFun2(DropdownMenuAction action) EditorConnection.instance.UnregisterDisconnection(OnHandleDisconnectionEvent);
{ EditorConnection.instance.Unregister(RemoteDebuggerDefine.kMsgSendPlayerToEditor, OnHandlePlayerMessage);
if (_viewMode == EViewMode.BundleView) _playerSessions.Clear();
return DropdownMenuAction.Status.Checked; }
else
return DropdownMenuAction.Status.Normal; 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}";
RemovePlayerSession(playerId);
}
private void OnHandlePlayerMessage(MessageEventArgs args)
{
var debugReport = DebugReport.Deserialize(args.data);
OnHandleDebugReport(args.playerId, debugReport);
}
private void OnHandleDebugReport(int playerId, DebugReport debugReport)
{
var playerSession = GetOrCreatePlayerSession(playerId);
playerSession.AddDebugReport(debugReport);
_debugReport = debugReport;
_assetListViewer.FillViewData(debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(debugReport, _searchKeyWord);
}
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 RemovePlayerSession(int playerId)
{
if (_playerSessions.ContainsKey(playerId))
_playerSessions.Remove(playerId);
}
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 (_debugReport != null)
{
_assetListViewer.FillViewData(_debugReport, _searchKeyWord);
_bundleListViewer.FillViewData(_debugReport, _searchKeyWord);
}
}
private void ViewModeMenuAction(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode != viewMode)
{
_viewMode = viewMode;
VisualElement root = this.rootVisualElement;
_viewModeMenu.text = viewMode.ToString();
_assetListViewer.AttachParent(root);
_bundleListViewer.DetachParent();
}
}
private DropdownMenuAction.Status ViewModeMenuFun(DropdownMenuAction action)
{
var viewMode = (EViewMode)action.userData;
if (_viewMode == viewMode)
return DropdownMenuAction.Status.Checked;
else
return DropdownMenuAction.Status.Normal;
}
}
} }
#endif #endif

View File

@@ -1,5 +1,6 @@
<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"> <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:Toolbar name="Toolbar" 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: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: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: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;" />

View File

@@ -0,0 +1,51 @@
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 RemotePlayerSession(int playerId, int maxReportCount = 1000)
{
PlayerId = playerId;
MaxReportCount = maxReportCount;
}
/// <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 GetLatestReport()
{
if (_reportList.Count == 0)
return null;
return _reportList[_reportList.Count - 1];
}
}
}

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 namespace YooAsset.Editor
{ {
internal class AssetListDebuggerViewer internal class DebuggerAssetListViewer
{ {
private VisualTreeAsset _visualAsset; private VisualTreeAsset _visualAsset;
private TemplateContainer _root; private TemplateContainer _root;
@@ -23,15 +23,11 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public void InitViewer() public void InitViewer()
{ {
// 加载布局文件 // 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath(); _visualAsset = EditorHelper.LoadWindowUXML<DebuggerAssetListViewer>();
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/VisualViewers/{nameof(AssetListDebuggerViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (_visualAsset == null) if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetListDebuggerViewer)}.uxml : {uxml}");
return; return;
}
_root = _visualAsset.CloneTree(); _root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f; _root.style.flexGrow = 1f;
@@ -175,7 +171,7 @@ namespace YooAsset.Editor
// Status // Status
StyleColor textColor; StyleColor textColor;
if (providerInfo.Status == ProviderBase.EStatus.Fail) if (providerInfo.Status == (int)ProviderBase.EStatus.Fail)
textColor = new StyleColor(Color.yellow); textColor = new StyleColor(Color.yellow);
else else
textColor = label1.style.color; textColor = label1.style.color;

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
internal class BundleListDebuggerViewer internal class DebuggerBundleListViewer
{ {
private VisualTreeAsset _visualAsset; private VisualTreeAsset _visualAsset;
private TemplateContainer _root; private TemplateContainer _root;
@@ -24,14 +24,10 @@ namespace YooAsset.Editor
public void InitViewer() public void InitViewer()
{ {
// 加载布局文件 // 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath(); _visualAsset = EditorHelper.LoadWindowUXML<DebuggerBundleListViewer>();
string uxml = $"{rootPath}/Editor/AssetBundleDebugger/VisualViewers/{nameof(BundleListDebuggerViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (_visualAsset == null) if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(BundleListDebuggerViewer)}.uxml : {uxml}");
return; return;
}
_root = _visualAsset.CloneTree(); _root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f; _root.style.flexGrow = 1f;
@@ -39,12 +35,12 @@ namespace YooAsset.Editor
_bundleListView = _root.Q<ListView>("TopListView"); _bundleListView = _root.Q<ListView>("TopListView");
_bundleListView.makeItem = MakeAssetListViewItem; _bundleListView.makeItem = MakeAssetListViewItem;
_bundleListView.bindItem = BindAssetListViewItem; _bundleListView.bindItem = BindAssetListViewItem;
#if UNITY_2020_1_OR_NEWER #if UNITY_2020_1_OR_NEWER
_bundleListView.onSelectionChange += BundleListView_onSelectionChange; _bundleListView.onSelectionChange += BundleListView_onSelectionChange;
#else #else
_bundleListView.onSelectionChanged += BundleListView_onSelectionChange; _bundleListView.onSelectionChanged += BundleListView_onSelectionChange;
#endif #endif
// 使用列表 // 使用列表
_usingListView = _root.Q<ListView>("BottomListView"); _usingListView = _root.Q<ListView>("BottomListView");
_usingListView.makeItem = MakeIncludeListViewItem; _usingListView.makeItem = MakeIncludeListViewItem;
@@ -151,7 +147,7 @@ namespace YooAsset.Editor
// Status // Status
StyleColor textColor; StyleColor textColor;
if (bundleInfo.Status == AssetBundleLoaderBase.EStatus.Failed) if (bundleInfo.Status == (int)AssetBundleLoaderBase.EStatus.Failed)
textColor = new StyleColor(Color.yellow); textColor = new StyleColor(Color.yellow);
else else
textColor = label1.style.color; textColor = label1.style.color;

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 #if UNITY_2019_4_OR_NEWER
using System;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEditor.UIElements; using UnityEditor.UIElements;
@@ -37,60 +38,68 @@ namespace YooAsset.Editor
} }
private ToolbarMenu _viewModeMenu; private ToolbarMenu _viewModeMenu;
private SummaryReporterViewer _summaryViewer; private ReporterSummaryViewer _summaryViewer;
private AssetListReporterViewer _assetListViewer; private ReporterAssetListViewer _assetListViewer;
private BundleListReporterViewer _bundleListViewer; private ReporterBundleListViewer _bundleListViewer;
private EViewMode _viewMode; private EViewMode _viewMode;
private string _searchKeyWord;
private BuildReport _buildReport; private BuildReport _buildReport;
private string _reportFilePath;
private string _searchKeyWord;
public void CreateGUI() public void CreateGUI()
{ {
VisualElement root = this.rootVisualElement; try
// 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/{nameof(AssetBundleReporterWindow)}.uxml";
var visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (visualAsset == null)
{ {
Debug.LogError($"Not found {nameof(AssetBundleReporterWindow)}.uxml : {uxml}"); VisualElement root = this.rootVisualElement;
return;
// 加载布局文件
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); catch (Exception e)
{
// 导入按钮 Debug.LogError(e.ToString());
var importBtn = root.Q<Button>("ImportButton"); }
importBtn.clicked += ImportBtn_onClick; }
public void OnDestroy()
// 视图模式菜单 {
_viewModeMenu = root.Q<ToolbarMenu>("ViewModeMenu"); AssetBundleRecorder.UnloadAll();
_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);
} }
private void ImportBtn_onClick() private void ImportBtn_onClick()
@@ -99,19 +108,20 @@ namespace YooAsset.Editor
if (string.IsNullOrEmpty(selectFilePath)) if (string.IsNullOrEmpty(selectFilePath))
return; return;
string jsonData = FileUtility.ReadFile(selectFilePath); _reportFilePath = selectFilePath;
string jsonData = FileUtility.ReadFile(_reportFilePath);
_buildReport = BuildReport.Deserialize(jsonData); _buildReport = BuildReport.Deserialize(jsonData);
_assetListViewer.FillViewData(_buildReport, _searchKeyWord); _assetListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _searchKeyWord); _bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord);
_summaryViewer.FillViewData(_buildReport); _summaryViewer.FillViewData(_buildReport);
} }
private void OnSearchKeyWordChange(ChangeEvent<string> e) private void OnSearchKeyWordChange(ChangeEvent<string> e)
{ {
_searchKeyWord = e.newValue; _searchKeyWord = e.newValue;
if(_buildReport != null) if (_buildReport != null)
{ {
_assetListViewer.FillViewData(_buildReport, _searchKeyWord); _assetListViewer.FillViewData(_buildReport, _searchKeyWord);
_bundleListViewer.FillViewData(_buildReport, _searchKeyWord); _bundleListViewer.FillViewData(_buildReport, _reportFilePath, _searchKeyWord);
} }
} }
private void ViewModeMenuAction0(DropdownMenuAction action) private void ViewModeMenuAction0(DropdownMenuAction action)

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
internal class AssetListReporterViewer internal class ReporterAssetListViewer
{ {
private enum ESortMode private enum ESortMode
{ {
@@ -38,48 +38,36 @@ namespace YooAsset.Editor
public void InitViewer() public void InitViewer()
{ {
// 加载布局文件 // 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath(); _visualAsset = EditorHelper.LoadWindowUXML<ReporterAssetListViewer>();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/VisualViewers/{nameof(AssetListReporterViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (_visualAsset == null) if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(AssetListReporterViewer)}.uxml : {uxml}");
return; return;
}
try _root = _visualAsset.CloneTree();
{ _root.style.flexGrow = 1f;
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
// 顶部按钮栏 // 顶部按钮栏
_topBar1 = _root.Q<ToolbarButton>("TopBar1"); _topBar1 = _root.Q<ToolbarButton>("TopBar1");
_topBar2 = _root.Q<ToolbarButton>("TopBar2"); _topBar2 = _root.Q<ToolbarButton>("TopBar2");
_topBar1.clicked += TopBar1_clicked; _topBar1.clicked += TopBar1_clicked;
_topBar2.clicked += TopBar2_clicked; _topBar2.clicked += TopBar2_clicked;
// 底部按钮栏 // 底部按钮栏
_bottomBar1 = _root.Q<ToolbarButton>("BottomBar1"); _bottomBar1 = _root.Q<ToolbarButton>("BottomBar1");
// 资源列表 // 资源列表
_assetListView = _root.Q<ListView>("TopListView"); _assetListView = _root.Q<ListView>("TopListView");
_assetListView.makeItem = MakeAssetListViewItem; _assetListView.makeItem = MakeAssetListViewItem;
_assetListView.bindItem = BindAssetListViewItem; _assetListView.bindItem = BindAssetListViewItem;
#if UNITY_2020_1_OR_NEWER #if UNITY_2020_1_OR_NEWER
_assetListView.onSelectionChange += AssetListView_onSelectionChange; _assetListView.onSelectionChange += AssetListView_onSelectionChange;
#else #else
_assetListView.onSelectionChanged += AssetListView_onSelectionChange; _assetListView.onSelectionChanged += AssetListView_onSelectionChange;
#endif #endif
// 依赖列表 // 依赖列表
_dependListView = _root.Q<ListView>("BottomListView"); _dependListView = _root.Q<ListView>("BottomListView");
_dependListView.makeItem = MakeDependListViewItem; _dependListView.makeItem = MakeDependListViewItem;
_dependListView.bindItem = BindDependListViewItem; _dependListView.bindItem = BindDependListViewItem;
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
} }
/// <summary> /// <summary>
@@ -322,7 +310,7 @@ namespace YooAsset.Editor
// Size // Size
var label2 = element.Q<Label>("Label2"); var label2 = element.Q<Label>("Label2");
label2.text = (bundleInfo.SizeBytes / 1024f).ToString("f1") + " KB"; label2.text = EditorUtility.FormatBytes(bundleInfo.SizeBytes);
// Hash // Hash
var label3 = element.Q<Label>("Label3"); var label3 = element.Q<Label>("Label3");

View File

@@ -10,7 +10,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
internal class BundleListReporterViewer internal class ReporterBundleListViewer
{ {
private enum ESortMode private enum ESortMode
{ {
@@ -31,71 +31,60 @@ namespace YooAsset.Editor
private ListView _includeListView; private ListView _includeListView;
private BuildReport _buildReport; private BuildReport _buildReport;
private string _reportFilePath;
private string _searchKeyWord; private string _searchKeyWord;
private ESortMode _sortMode = ESortMode.BundleName; private ESortMode _sortMode = ESortMode.BundleName;
private bool _descendingSort = false; private bool _descendingSort = false;
/// <summary> /// <summary>
/// 初始化页面 /// 初始化页面
/// </summary> /// </summary>
public void InitViewer() public void InitViewer()
{ {
// 加载布局文件 // 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath(); _visualAsset = EditorHelper.LoadWindowUXML<ReporterBundleListViewer>();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/VisualViewers/{nameof(BundleListReporterViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (_visualAsset == null) if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(BundleListReporterViewer)}.uxml : {uxml}");
return; return;
}
try _root = _visualAsset.CloneTree();
{ _root.style.flexGrow = 1f;
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
// 顶部按钮栏 // 顶部按钮栏
_topBar1 = _root.Q<ToolbarButton>("TopBar1"); _topBar1 = _root.Q<ToolbarButton>("TopBar1");
_topBar2 = _root.Q<ToolbarButton>("TopBar2"); _topBar2 = _root.Q<ToolbarButton>("TopBar2");
_topBar3 = _root.Q<ToolbarButton>("TopBar3"); _topBar3 = _root.Q<ToolbarButton>("TopBar3");
_topBar4 = _root.Q<ToolbarButton>("TopBar4"); _topBar4 = _root.Q<ToolbarButton>("TopBar4");
_topBar1.clicked += TopBar1_clicked; _topBar1.clicked += TopBar1_clicked;
_topBar2.clicked += TopBar2_clicked; _topBar2.clicked += TopBar2_clicked;
_topBar3.clicked += TopBar3_clicked; _topBar3.clicked += TopBar3_clicked;
_topBar4.clicked += TopBar4_clicked; _topBar4.clicked += TopBar4_clicked;
// 底部按钮栏 // 底部按钮栏
_bottomBar1 = _root.Q<ToolbarButton>("BottomBar1"); _bottomBar1 = _root.Q<ToolbarButton>("BottomBar1");
// 资源包列表 // 资源包列表
_bundleListView = _root.Q<ListView>("TopListView"); _bundleListView = _root.Q<ListView>("TopListView");
_bundleListView.makeItem = MakeBundleListViewItem; _bundleListView.makeItem = MakeBundleListViewItem;
_bundleListView.bindItem = BindBundleListViewItem; _bundleListView.bindItem = BindBundleListViewItem;
#if UNITY_2020_1_OR_NEWER #if UNITY_2020_1_OR_NEWER
_bundleListView.onSelectionChange += BundleListView_onSelectionChange; _bundleListView.onSelectionChange += BundleListView_onSelectionChange;
#else #else
_bundleListView.onSelectionChanged += BundleListView_onSelectionChange; _bundleListView.onSelectionChanged += BundleListView_onSelectionChange;
#endif #endif
// 包含列表 // 包含列表
_includeListView = _root.Q<ListView>("BottomListView"); _includeListView = _root.Q<ListView>("BottomListView");
_includeListView.makeItem = MakeIncludeListViewItem; _includeListView.makeItem = MakeIncludeListViewItem;
_includeListView.bindItem = BindIncludeListViewItem; _includeListView.bindItem = BindIncludeListViewItem;
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
} }
/// <summary> /// <summary>
/// 填充页面数据 /// 填充页面数据
/// </summary> /// </summary>
public void FillViewData(BuildReport buildReport, string searchKeyWord) public void FillViewData(BuildReport buildReport, string reprotFilePath, string searchKeyWord)
{ {
_buildReport = buildReport; _buildReport = buildReport;
_reportFilePath = reprotFilePath;
_searchKeyWord = searchKeyWord; _searchKeyWord = searchKeyWord;
RefreshView(); RefreshView();
} }
@@ -139,7 +128,7 @@ namespace YooAsset.Editor
} }
else if (_sortMode == ESortMode.BundleTags) else if (_sortMode == ESortMode.BundleTags)
{ {
if(_descendingSort) if (_descendingSort)
return result.OrderByDescending(a => a.GetTagsString()).ToList(); return result.OrderByDescending(a => a.GetTagsString()).ToList();
else else
return result.OrderBy(a => a.GetTagsString()).ToList(); return result.OrderBy(a => a.GetTagsString()).ToList();
@@ -171,7 +160,7 @@ namespace YooAsset.Editor
else else
_topBar2.text = "Size ↑"; _topBar2.text = "Size ↑";
} }
else if(_sortMode == ESortMode.BundleTags) else if (_sortMode == ESortMode.BundleTags)
{ {
if (_descendingSort) if (_descendingSort)
_topBar4.text = "Tags ↓"; _topBar4.text = "Tags ↓";
@@ -260,7 +249,7 @@ namespace YooAsset.Editor
// Size // Size
var label2 = element.Q<Label>("Label2"); var label2 = element.Q<Label>("Label2");
label2.text = (bundleInfo.SizeBytes / 1024f).ToString("f1") + " KB"; label2.text = EditorUtility.FormatBytes(bundleInfo.SizeBytes);
// Hash // Hash
var label3 = element.Q<Label>("Label3"); var label3 = element.Q<Label>("Label3");
@@ -276,8 +265,22 @@ namespace YooAsset.Editor
{ {
ReportBundleInfo bundleInfo = item as ReportBundleInfo; ReportBundleInfo bundleInfo = item as ReportBundleInfo;
FillIncludeListView(bundleInfo); FillIncludeListView(bundleInfo);
ShowAssetBundleInspector(bundleInfo);
break;
} }
} }
private void ShowAssetBundleInspector(ReportBundleInfo bundleInfo)
{
if (bundleInfo.IsRawFile())
return;
string rootDirectory = Path.GetDirectoryName(_reportFilePath);
string filePath = $"{rootDirectory}/{bundleInfo.Hash}";
if (File.Exists(filePath))
Selection.activeObject = AssetBundleRecorder.GetAssetBundle(filePath);
else
Selection.activeObject = null;
}
private void TopBar1_clicked() private void TopBar1_clicked()
{ {
if (_sortMode != ESortMode.BundleName) if (_sortMode != ESortMode.BundleName)

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
internal class SummaryReporterViewer internal class ReporterSummaryViewer
{ {
private class ItemWrapper private class ItemWrapper
{ {
@@ -37,14 +37,10 @@ namespace YooAsset.Editor
public void InitViewer() public void InitViewer()
{ {
// 加载布局文件 // 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath(); _visualAsset = EditorHelper.LoadWindowUXML<ReporterSummaryViewer>();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/VisualViewers/{nameof(SummaryReporterViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
if (_visualAsset == null) if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(SummaryReporterViewer)}.uxml : {uxml}");
return; return;
}
_root = _visualAsset.CloneTree(); _root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f; _root.style.flexGrow = 1f;
@@ -71,8 +67,8 @@ namespace YooAsset.Editor
_items.Add(new ItemWrapper("内置资源标签", $"{buildReport.Summary.BuildinTags}")); _items.Add(new ItemWrapper("内置资源标签", $"{buildReport.Summary.BuildinTags}"));
_items.Add(new ItemWrapper("启用可寻址资源定位", $"{buildReport.Summary.EnableAddressable}")); _items.Add(new ItemWrapper("启用可寻址资源定位", $"{buildReport.Summary.EnableAddressable}"));
_items.Add(new ItemWrapper("启用自动分包机制", $"{buildReport.Summary.EnableAutoCollect}"));
_items.Add(new ItemWrapper("追加文件扩展名", $"{buildReport.Summary.AppendFileExtension}")); _items.Add(new ItemWrapper("追加文件扩展名", $"{buildReport.Summary.AppendFileExtension}"));
_items.Add(new ItemWrapper("拷贝内置资源文件", $"{buildReport.Summary.CopyBuildinTagFiles}"));
_items.Add(new ItemWrapper("自动收集着色器", $"{buildReport.Summary.AutoCollectShaders}")); _items.Add(new ItemWrapper("自动收集着色器", $"{buildReport.Summary.AutoCollectShaders}"));
_items.Add(new ItemWrapper("着色器资源包名称", $"{buildReport.Summary.ShadersBundleName}")); _items.Add(new ItemWrapper("着色器资源包名称", $"{buildReport.Summary.ShadersBundleName}"));
_items.Add(new ItemWrapper("加密服务类名称", $"{buildReport.Summary.EncryptionServicesClassName}")); _items.Add(new ItemWrapper("加密服务类名称", $"{buildReport.Summary.EncryptionServicesClassName}"));
@@ -80,10 +76,8 @@ namespace YooAsset.Editor
_items.Add(new ItemWrapper(string.Empty, string.Empty)); _items.Add(new ItemWrapper(string.Empty, string.Empty));
_items.Add(new ItemWrapper("构建参数", string.Empty)); _items.Add(new ItemWrapper("构建参数", string.Empty));
_items.Add(new ItemWrapper("CompressOption", $"{buildReport.Summary.CompressOption}")); _items.Add(new ItemWrapper("CompressOption", $"{buildReport.Summary.CompressOption}"));
_items.Add(new ItemWrapper("AppendHash", $"{buildReport.Summary.AppendHash}"));
_items.Add(new ItemWrapper("DisableWriteTypeTree", $"{buildReport.Summary.DisableWriteTypeTree}")); _items.Add(new ItemWrapper("DisableWriteTypeTree", $"{buildReport.Summary.DisableWriteTypeTree}"));
_items.Add(new ItemWrapper("IgnoreTypeTreeChanges", $"{buildReport.Summary.IgnoreTypeTreeChanges}")); _items.Add(new ItemWrapper("IgnoreTypeTreeChanges", $"{buildReport.Summary.IgnoreTypeTreeChanges}"));
_items.Add(new ItemWrapper("DisableLoadAssetByFileName", $"{buildReport.Summary.DisableLoadAssetByFileName}"));
_items.Add(new ItemWrapper(string.Empty, string.Empty)); _items.Add(new ItemWrapper(string.Empty, string.Empty));
_items.Add(new ItemWrapper("构建结果", string.Empty)); _items.Add(new ItemWrapper("构建结果", string.Empty));

View File

@@ -4,10 +4,12 @@ namespace YooAsset.Editor
{ {
public class EditorDefine public class EditorDefine
{ {
#if UNITY_2019_4_OR_NEWER
/// <summary> /// <summary>
/// 停靠窗口类型集合 /// 停靠窗口类型集合
/// </summary> /// </summary>
public static readonly Type[] DockedWindowTypes = { typeof(AssetBundleBuilderWindow), typeof(AssetBundleGrouperWindow), typeof(AssetBundleDebuggerWindow), typeof(AssetBundleReporterWindow)}; public static readonly Type[] DockedWindowTypes = { typeof(AssetBundleBuilderWindow), typeof(AssetBundleCollectorWindow), typeof(AssetBundleDebuggerWindow), typeof(AssetBundleReporterWindow)};
#endif
} }
/// <summary> /// <summary>

View File

@@ -1,6 +1,7 @@
 
namespace YooAsset.Editor namespace YooAsset.Editor
{ {
#if UNITY_2019 #if UNITY_2019
public static partial class UnityEngine_UIElements_ListView_Extension public static partial class UnityEngine_UIElements_ListView_Extension
{ {
@@ -20,4 +21,5 @@ namespace YooAsset.Editor
} }
} }
#endif #endif
} }

View File

@@ -0,0 +1,91 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace YooAsset.Editor
{
public class EditorHelper
{
#if UNITY_2019_4_OR_NEWER
private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>();
static EditorHelper()
{
// 资源包收集
_uxmlDic.Add(typeof(AssetBundleCollectorWindow), "355c4ac5cdebddc4c8362bed6f17a79e");
// 资源包构建
_uxmlDic.Add(typeof(AssetBundleBuilderWindow), "28ba29adb4949284e8c48893218b0d9a");
// 资源包调试
_uxmlDic.Add(typeof(AssetBundleDebuggerWindow), "790db12999afd334e8fb6ba70ef0a947");
_uxmlDic.Add(typeof(DebuggerAssetListViewer), "31c6096c1cb29b4469096b7b4942a322");
_uxmlDic.Add(typeof(DebuggerBundleListViewer), "932a25ffd05c13c47994d66e9d73bc37");
// 构建报告
_uxmlDic.Add(typeof(AssetBundleReporterWindow), "9052b72c383e95043a0c7e7f369b1ad7");
_uxmlDic.Add(typeof(ReporterSummaryViewer), "f8929271050855e42a1ccc6b14993a04");
_uxmlDic.Add(typeof(ReporterAssetListViewer), "5f81bc15a55ee0a49a266f9d71e2372b");
_uxmlDic.Add(typeof(ReporterBundleListViewer), "56d6dbe0d65ce334a8996beb19612989");
}
/// <summary>
/// 加载窗口的布局文件
/// </summary>
public static UnityEngine.UIElements.VisualTreeAsset LoadWindowUXML<TWindow>() where TWindow : class
{
var windowType = typeof(TWindow);
if (_uxmlDic.TryGetValue(windowType, out string uxmlGUID))
{
string assetPath = AssetDatabase.GUIDToAssetPath(uxmlGUID);
if (string.IsNullOrEmpty(assetPath))
throw new System.Exception($"Invalid YooAsset uxml guid : {uxmlGUID}");
var visualTreeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
if (visualTreeAsset == null)
throw new System.Exception($"Failed to load {windowType}.uxml");
return visualTreeAsset;
}
else
{
throw new System.Exception($"Invalid YooAsset window type : {windowType}");
}
}
#endif
/// <summary>
/// 加载相关的配置文件
/// </summary>
public static TSetting LoadSettingData<TSetting>() where TSetting : ScriptableObject
{
var settingType = typeof(TSetting);
var guids = AssetDatabase.FindAssets($"t:{settingType.Name}");
if (guids.Length == 0)
{
Debug.LogWarning($"Create new {settingType.Name}.asset");
var setting = ScriptableObject.CreateInstance<TSetting>();
string filePath = $"Assets/{settingType.Name}.asset";
AssetDatabase.CreateAsset(setting, filePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return setting;
}
else
{
if (guids.Length != 1)
{
foreach (var guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
Debug.LogWarning($"Found multiple file : {path}");
}
throw new System.Exception($"Found multiple {settingType.Name} files !");
}
string filePath = AssetDatabase.GUIDToAssetPath(guids[0]);
var setting = AssetDatabase.LoadAssetAtPath<TSetting>(filePath);
return setting;
}
}
}
}

View File

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

View File

@@ -1,10 +1,10 @@
using System.Collections; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Linq; using System.Linq;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
@@ -15,7 +15,57 @@ namespace YooAsset.Editor
/// </summary> /// </summary>
public static class EditorTools public static class EditorTools
{ {
static EditorTools()
{
InitAssembly();
}
#region Assembly #region Assembly
#if UNITY_2019_4_OR_NEWER
private static void InitAssembly()
{
}
/// <summary>
/// 获取带继承关系的所有类的类型
/// </summary>
public static List<Type> GetAssignableTypes(System.Type parentType)
{
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom(parentType);
return collection.ToList();
}
#else
private static readonly List<Type> _cacheTypes = new List<Type>(10000);
private static void InitAssembly()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
List<Type> types = assembly.GetTypes().ToList();
_cacheTypes.AddRange(types);
}
}
/// <summary>
/// 获取带继承关系的所有类的类型
/// </summary>
public static List<Type> GetAssignableTypes(System.Type parentType)
{
List<Type> result = new List<Type>();
for (int i = 0; i < _cacheTypes.Count; i++)
{
Type type = _cacheTypes[i];
if (parentType.IsAssignableFrom(type))
{
if (type.Name == parentType.Name)
continue;
result.Add(type);
}
}
return result;
}
#endif
/// <summary> /// <summary>
/// 调用私有的静态方法 /// 调用私有的静态方法
/// </summary> /// </summary>
@@ -190,7 +240,7 @@ namespace YooAsset.Editor
} }
#endregion #endregion
#region #region EditorConsole
private static MethodInfo _clearConsoleMethod; private static MethodInfo _clearConsoleMethod;
private static MethodInfo ClearConsoleMethod private static MethodInfo ClearConsoleMethod
{ {
@@ -412,9 +462,6 @@ namespace YooAsset.Editor
#endregion #endregion
#region #region
private static string YooAssetSourcePath;
private static string YooAssetSettingPath;
/// <summary> /// <summary>
/// 获取规范的路径 /// 获取规范的路径
/// </summary> /// </summary>
@@ -423,83 +470,6 @@ namespace YooAsset.Editor
return path.Replace('\\', '/').Replace("\\", "/"); //替换为Linux路径格式 return path.Replace('\\', '/').Replace("\\", "/"); //替换为Linux路径格式
} }
/// <summary>
/// 获取资源框架源码路径
/// </summary>
public static string GetYooAssetSourcePath()
{
if (string.IsNullOrEmpty(YooAssetSourcePath) == false)
{
if (Directory.Exists(YooAssetSourcePath))
return YooAssetSourcePath;
}
// 从Pakcages目录下搜索
string packagesPath = "Packages/com.tuyoogame.yooasset/README.md";
var obj = AssetDatabase.LoadAssetAtPath(packagesPath, typeof(TextAsset));
if (obj != null)
{
YooAssetSourcePath = "Packages/com.tuyoogame.yooasset/";
return YooAssetSourcePath;
}
// 从Assets目录下搜索
string[] allDirectorys = Directory.GetDirectories(Application.dataPath, "YooAsset", SearchOption.AllDirectories);
if (allDirectorys.Length == 0)
{
Debug.LogError("Not found YooAsset package !");
return string.Empty;
}
string targetDirectory = string.Empty;
foreach (var directory in allDirectorys)
{
string asmdefFilePath = $"{directory}/Editor/YooAsset.Editor.asmdef";
if (File.Exists(asmdefFilePath))
{
targetDirectory = directory;
break;
}
}
if (string.IsNullOrEmpty(targetDirectory))
{
Debug.LogError("Should never get here !");
return string.Empty;
}
YooAssetSourcePath = AbsolutePathToAssetPath(targetDirectory);
return YooAssetSourcePath;
}
/// <summary>
/// 获取资源框架配置路径
/// </summary>
public static string GetYooAssetSettingPath()
{
if (string.IsNullOrEmpty(YooAssetSettingPath) == false)
{
if (Directory.Exists(YooAssetSettingPath))
return YooAssetSettingPath;
}
// 从Assets目录下搜索
string[] allDirectorys = Directory.GetDirectories(Application.dataPath, "YooAssetSetting", SearchOption.AllDirectories);
if (allDirectorys.Length == 0)
{
YooAssetSettingPath = "Assets/YooAssetSetting";
return YooAssetSettingPath;
}
string targetDirectory = allDirectorys[0];
if (allDirectorys.Length != 1)
{
Debug.LogError("Found multiple YooAssetSetting folder !");
}
YooAssetSettingPath = AbsolutePathToAssetPath(targetDirectory);
return YooAssetSettingPath;
}
/// <summary> /// <summary>
/// 获取项目工程路径 /// 获取项目工程路径
/// </summary> /// </summary>
@@ -516,7 +486,7 @@ namespace YooAsset.Editor
public static string AbsolutePathToAssetPath(string absolutePath) public static string AbsolutePathToAssetPath(string absolutePath)
{ {
string content = GetRegularPath(absolutePath); string content = GetRegularPath(absolutePath);
return Substring(content, "Assets", true); return Substring(content, "Assets/", true);
} }
/// <summary> /// <summary>
@@ -551,40 +521,6 @@ namespace YooAsset.Editor
} }
return string.Empty; return string.Empty;
} }
#endregion
#region
/// <summary>
/// 是否含有中文
/// </summary>
public static bool IncludeChinese(string content)
{
foreach (var c in content)
{
if (c >= 0x4e00 && c <= 0x9fbb)
return true;
}
return false;
}
/// <summary>
/// 是否是数字
/// </summary>
public static bool IsNumber(string content)
{
if (string.IsNullOrEmpty(content))
return false;
string pattern = @"^\d*$";
return Regex.IsMatch(content, pattern);
}
/// <summary>
/// 首字母大写
/// </summary>
public static string Capitalize(string content)
{
return content.Substring(0, 1).ToUpper() + (content.Length > 1 ? content.Substring(1).ToLower() : "");
}
/// <summary> /// <summary>
/// 截取字符串 /// 截取字符串
@@ -594,7 +530,7 @@ namespace YooAsset.Editor
/// <param name="key">关键字</param> /// <param name="key">关键字</param>
/// <param name="includeKey">分割的结果里是否包含关键字</param> /// <param name="includeKey">分割的结果里是否包含关键字</param>
/// <param name="searchBegin">是否使用初始匹配的位置,否则使用末尾匹配的位置</param> /// <param name="searchBegin">是否使用初始匹配的位置,否则使用末尾匹配的位置</param>
public static string Substring(string content, string key, bool includeKey, bool firstMatch = true) private static string Substring(string content, string key, bool includeKey, bool firstMatch = true)
{ {
if (string.IsNullOrEmpty(key)) if (string.IsNullOrEmpty(key))
return content; return content;

View File

@@ -98,7 +98,7 @@ namespace YooAsset.Editor
List<string> allAssets = new List<string>(1000); List<string> allAssets = new List<string>(1000);
// 获取所有打包的资源 // 获取所有打包的资源
List<CollectAssetInfo> allCollectInfos = AssetBundleGrouperSettingData.Setting.GetAllCollectAssets(); List<CollectAssetInfo> allCollectInfos = AssetBundleCollectorSettingData.Setting.GetAllCollectAssets(EBuildMode.DryRunBuild);
List<string> collectAssets = allCollectInfos.Select(t => t.AssetPath).ToList(); List<string> collectAssets = allCollectInfos.Select(t => t.AssetPath).ToList();
foreach (var assetPath in collectAssets) foreach (var assetPath in collectAssets)
{ {

View File

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

View File

@@ -1,7 +1,6 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
@@ -11,36 +10,31 @@ namespace YooAsset
{ {
private static readonly List<AssetBundleLoaderBase> _loaders = new List<AssetBundleLoaderBase>(1000); private static readonly List<AssetBundleLoaderBase> _loaders = new List<AssetBundleLoaderBase>(1000);
private static readonly List<ProviderBase> _providers = new List<ProviderBase>(1000); private static readonly List<ProviderBase> _providers = new List<ProviderBase>(1000);
private static readonly HashSet<AssetOperationHandle> _trackGameObjectHandles = new HashSet<AssetOperationHandle>();
private static readonly Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100); private static readonly Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100);
private static bool _simulationOnEditor;
/// <summary> private static int _loadingMaxNumber;
/// 在编辑器下模拟运行
/// </summary>
public static bool SimulationOnEditor { private set; get; }
/// <summary>
/// 运行时的最大加载个数
/// </summary>
public static int AssetLoadingMaxNumber { private set; get; }
public static bool AutoReleaseGameObjectHandle { private set; get; }
public static IDecryptionServices DecryptionServices { private set; get; } public static IDecryptionServices DecryptionServices { private set; get; }
public static IBundleServices BundleServices { private set; get; } public static IBundleServices BundleServices { private set; get; }
/// <summary> /// <summary>
/// 初始化资源系统 /// 初始化
/// 注意在使用AssetSystem之前需要初始化 /// 注意在使用AssetSystem之前需要初始化
/// </summary> /// </summary>
public static void Initialize(bool simulationOnEditor, int assetLoadingMaxNumber, IDecryptionServices decryptionServices, IBundleServices bundleServices) public static void Initialize(bool simulationOnEditor, int loadingMaxNumber, bool autoReleaseGameObjectHandle, IDecryptionServices decryptionServices, IBundleServices bundleServices)
{ {
SimulationOnEditor = simulationOnEditor; _simulationOnEditor = simulationOnEditor;
AssetLoadingMaxNumber = assetLoadingMaxNumber; _loadingMaxNumber = loadingMaxNumber;
AutoReleaseGameObjectHandle = autoReleaseGameObjectHandle;
DecryptionServices = decryptionServices; DecryptionServices = decryptionServices;
BundleServices = bundleServices; BundleServices = bundleServices;
} }
/// <summary> /// <summary>
/// 轮询更新 /// 更新
/// </summary> /// </summary>
public static void Update() public static void Update()
{ {
@@ -63,7 +57,7 @@ namespace YooAsset
} }
else else
{ {
if (loadingCount < AssetLoadingMaxNumber) if (loadingCount < _loadingMaxNumber)
provider.Update(); provider.Update();
if (provider.IsDone == false) if (provider.IsDone == false)
@@ -72,12 +66,30 @@ namespace YooAsset
} }
} }
/// <summary>
/// 销毁
/// </summary>
public static void DestroyAll()
{
_loaders.Clear();
_providers.Clear();
_sceneHandles.Clear();
DecryptionServices = null;
BundleServices = null;
}
/// <summary> /// <summary>
/// 资源回收(卸载引用计数为零的资源) /// 资源回收(卸载引用计数为零的资源)
/// </summary> /// </summary>
public static void UnloadUnusedAssets() public static void UnloadUnusedAssets()
{ {
if (SimulationOnEditor) if (AutoReleaseGameObjectHandle)
{
CheckAutoReleaseGameObjectHandle();
}
if (_simulationOnEditor)
{ {
for (int i = _providers.Count - 1; i >= 0; i--) for (int i = _providers.Count - 1; i >= 0; i--)
{ {
@@ -128,15 +140,22 @@ namespace YooAsset
Resources.UnloadUnusedAssets(); Resources.UnloadUnusedAssets();
} }
/// <summary> /// <summary>
/// 异步加载场景 /// 加载场景
/// </summary> /// </summary>
public static SceneOperationHandle LoadSceneAsync(string scenePath, LoadSceneMode sceneMode, bool activateOnLoad, int priority) public static SceneOperationHandle LoadSceneAsync(AssetInfo assetInfo, LoadSceneMode sceneMode, bool activateOnLoad, int priority)
{ {
if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
return completedProvider.CreateHandle<SceneOperationHandle>();
}
// 注意:场景句柄永远保持唯一 // 注意:场景句柄永远保持唯一
if (_sceneHandles.ContainsKey(scenePath)) string providerGUID = assetInfo.ProviderGUID;
return _sceneHandles[scenePath]; if (_sceneHandles.ContainsKey(providerGUID))
return _sceneHandles[providerGUID];
// 如果加载的是主场景,则卸载所有缓存的场景 // 如果加载的是主场景,则卸载所有缓存的场景
if (sceneMode == LoadSceneMode.Single) if (sceneMode == LoadSceneMode.Single)
@@ -144,68 +163,104 @@ namespace YooAsset
UnloadAllScene(); UnloadAllScene();
} }
ProviderBase provider = TryGetProvider(scenePath); ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null) if (provider == null)
{ {
if (SimulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseSceneProvider(scenePath, sceneMode, activateOnLoad, priority); provider = new DatabaseSceneProvider(assetInfo, sceneMode, activateOnLoad, priority);
else else
provider = new BundledSceneProvider(scenePath, sceneMode, activateOnLoad, priority); provider = new BundledSceneProvider(assetInfo, sceneMode, activateOnLoad, priority);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providers.Add(provider);
} }
var handle = provider.CreateHandle() as SceneOperationHandle; var handle = provider.CreateHandle<SceneOperationHandle>();
_sceneHandles.Add(scenePath, handle); _sceneHandles.Add(providerGUID, handle);
return handle; return handle;
} }
/// <summary> /// <summary>
/// 异步加载资源对象 /// 加载资源对象
/// </summary> /// </summary>
public static AssetOperationHandle LoadAssetAsync(string assetPath, System.Type assetType) public static AssetOperationHandle LoadAssetAsync(AssetInfo assetInfo)
{ {
ProviderBase provider = TryGetProvider(assetPath); if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
return completedProvider.CreateHandle<AssetOperationHandle>();
}
ProviderBase provider = TryGetProvider(assetInfo.ProviderGUID);
if (provider == null) if (provider == null)
{ {
if (SimulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseAssetProvider(assetPath, assetType); provider = new DatabaseAssetProvider(assetInfo);
else else
provider = new BundledAssetProvider(assetPath, assetType); provider = new BundledAssetProvider(assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providers.Add(provider);
} }
return provider.CreateHandle() as AssetOperationHandle; return provider.CreateHandle<AssetOperationHandle>();
} }
/// <summary> /// <summary>
/// 异步加载所有子资源对象 /// 加载子资源对象
/// </summary> /// </summary>
public static SubAssetsOperationHandle LoadSubAssetsAsync(string assetPath, System.Type assetType) public static SubAssetsOperationHandle LoadSubAssetsAsync(AssetInfo assetInfo)
{ {
ProviderBase provider = TryGetProvider(assetPath); if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
CompletedProvider completedProvider = new CompletedProvider(assetInfo);
return completedProvider.CreateHandle<SubAssetsOperationHandle>();
}
ProviderBase provider = TryGetProvider(assetInfo.ProviderGUID);
if (provider == null) if (provider == null)
{ {
if (SimulationOnEditor) if (_simulationOnEditor)
provider = new DatabaseSubAssetsProvider(assetPath, assetType); provider = new DatabaseSubAssetsProvider(assetInfo);
else else
provider = new BundledSubAssetsProvider(assetPath, assetType); provider = new BundledSubAssetsProvider(assetInfo);
provider.InitSpawnDebugInfo(); provider.InitSpawnDebugInfo();
_providers.Add(provider); _providers.Add(provider);
} }
return provider.CreateHandle() as SubAssetsOperationHandle; return provider.CreateHandle<SubAssetsOperationHandle>();
} }
/// <summary>
/// 添加自动释放的游戏对象句柄
/// </summary>
public static void AddAutoReleaseGameObjectHandle(AssetOperationHandle handle)
{
if (_trackGameObjectHandles.Contains(handle) == false)
_trackGameObjectHandles.Add(handle);
}
private static void CheckAutoReleaseGameObjectHandle()
{
List<AssetOperationHandle> removeList = new List<AssetOperationHandle>();
foreach (var trackHandle in _trackGameObjectHandles)
{
trackHandle.CheckAutoReleaseHandle();
if (trackHandle.IsValidNoWarning == false)
removeList.Add(trackHandle);
}
foreach (var removeHandle in removeList)
{
_trackGameObjectHandles.Remove(removeHandle);
}
}
internal static void UnloadSubScene(ProviderBase provider) internal static void UnloadSubScene(ProviderBase provider)
{ {
string scenePath = provider.AssetPath; string providerGUID = provider.MainAssetInfo.ProviderGUID;
if (_sceneHandles.ContainsKey(scenePath) == false) if (_sceneHandles.ContainsKey(providerGUID) == false)
throw new Exception("Should never get here !"); throw new Exception("Should never get here !");
// 释放子场景句柄 // 释放子场景句柄
_sceneHandles[scenePath].ReleaseInternal(); _sceneHandles[providerGUID].ReleaseInternal();
_sceneHandles.Remove(scenePath); _sceneHandles.Remove(providerGUID);
// 卸载未被使用的资源(包括场景) // 卸载未被使用的资源(包括场景)
AssetSystem.UnloadUnusedAssets(); AssetSystem.UnloadUnusedAssets();
@@ -239,24 +294,19 @@ namespace YooAsset
} }
} }
internal static AssetBundleLoaderBase CreateOwnerAssetBundleLoader(string assetPath) internal static AssetBundleLoaderBase CreateOwnerAssetBundleLoader(AssetInfo assetInfo)
{ {
string bundleName = BundleServices.GetBundleName(assetPath); BundleInfo bundleInfo = BundleServices.GetBundleInfo(assetInfo);
BundleInfo bundleInfo = BundleServices.GetBundleInfo(bundleName);
return CreateAssetBundleLoaderInternal(bundleInfo); return CreateAssetBundleLoaderInternal(bundleInfo);
} }
internal static List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(string assetPath) internal static List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
{ {
List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>(); BundleInfo[] depends = BundleServices.GetAllDependBundleInfos(assetInfo);
string[] depends = BundleServices.GetAllDependencies(assetPath); List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>(depends.Length);
if (depends != null) foreach (var bundleInfo in depends)
{ {
foreach (var dependBundleName in depends) AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
{ result.Add(dependLoader);
BundleInfo dependBundleInfo = BundleServices.GetBundleInfo(dependBundleName);
AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(dependBundleInfo);
result.Add(dependLoader);
}
} }
return result; return result;
} }
@@ -291,7 +341,7 @@ namespace YooAsset
for (int i = 0; i < _loaders.Count; i++) for (int i = 0; i < _loaders.Count; i++)
{ {
AssetBundleLoaderBase temp = _loaders[i]; AssetBundleLoaderBase temp = _loaders[i];
if (temp.BundleFileInfo.BundleName.Equals(bundleName)) if (temp.MainBundleInfo.BundleName.Equals(bundleName))
{ {
loader = temp; loader = temp;
break; break;
@@ -299,13 +349,13 @@ namespace YooAsset
} }
return loader; return loader;
} }
private static ProviderBase TryGetProvider(string assetPath) private static ProviderBase TryGetProvider(string providerGUID)
{ {
ProviderBase provider = null; ProviderBase provider = null;
for (int i = 0; i < _providers.Count; i++) for (int i = 0; i < _providers.Count; i++)
{ {
ProviderBase temp = _providers[i]; ProviderBase temp = _providers[i];
if (temp.AssetPath.Equals(assetPath)) if (temp.MainAssetInfo.ProviderGUID.Equals(providerGUID))
{ {
provider = temp; provider = temp;
break; break;
@@ -314,23 +364,23 @@ namespace YooAsset
return provider; return provider;
} }
#region #region
internal static void GetDebugReport(DebugReport report) internal static DebugReport GetDebugReport()
{ {
report.ClearAll(); DebugReport report = new DebugReport();
report.FrameCount = Time.frameCount;
report.BundleCount = _loaders.Count; report.BundleCount = _loaders.Count;
report.AssetCount = _providers.Count; report.AssetCount = _providers.Count;
foreach (var provider in _providers) foreach (var provider in _providers)
{ {
DebugProviderInfo providerInfo = new DebugProviderInfo(); DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.AssetPath = provider.AssetPath; providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
providerInfo.SpawnScene = provider.SpawnScene; providerInfo.SpawnScene = provider.SpawnScene;
providerInfo.SpawnTime = provider.SpawnTime; providerInfo.SpawnTime = provider.SpawnTime;
providerInfo.RefCount = provider.RefCount; providerInfo.RefCount = provider.RefCount;
providerInfo.Status = provider.Status; providerInfo.Status = (int)provider.Status;
providerInfo.BundleInfos.Clear(); providerInfo.BundleInfos = new List<DebugBundleInfo>();
report.ProviderInfos.Add(providerInfo); report.ProviderInfos.Add(providerInfo);
if (provider is BundledProvider) if (provider is BundledProvider)
@@ -342,6 +392,7 @@ namespace YooAsset
// 重新排序 // 重新排序
report.ProviderInfos.Sort(); report.ProviderInfos.Sort();
return report;
} }
#endregion #endregion
} }

View File

@@ -1,4 +1,5 @@
using UnityEngine; using UnityEngine;
using System.Collections.Generic;
namespace YooAsset namespace YooAsset
{ {
@@ -117,26 +118,72 @@ namespace YooAsset
if (Provider.AssetObject == null) if (Provider.AssetObject == null)
return null; return null;
GameObject result;
if (setPositionRotation) if (setPositionRotation)
{ {
if (parent == null) if (parent == null)
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation); result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation);
else else
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation, parent); result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation, parent);
} }
else else
{ {
if (parent == null) if (parent == null)
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject); result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject);
else else
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, parent); result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, parent);
} }
if (AssetSystem.AutoReleaseGameObjectHandle)
{
AddTrackGameObject(result);
}
return result;
} }
private InstantiateOperation InstantiateAsyncInternal(Vector3 position, Quaternion rotation, Transform parent, bool setPositionRotation) private InstantiateOperation InstantiateAsyncInternal(Vector3 position, Quaternion rotation, Transform parent, bool setPositionRotation)
{ {
InstantiateOperation operation = new InstantiateOperation(this, position, rotation, parent, setPositionRotation); InstantiateOperation operation = new InstantiateOperation(this, position, rotation, parent, setPositionRotation);
OperationSystem.ProcessOperaiton(operation); OperationSystem.StartOperaiton(operation);
if (AssetSystem.AutoReleaseGameObjectHandle)
{
operation.Completed += InstantiateOperationCompleted;
}
return operation; return operation;
} }
#region
private readonly HashSet<GameObject> _trackGameObjects = new HashSet<GameObject>();
private void InstantiateOperationCompleted(AsyncOperationBase obj)
{
if (obj.Status == EOperationStatus.Succeed)
{
var op = obj as InstantiateOperation;
AddTrackGameObject(op.Result);
}
}
private void AddTrackGameObject(GameObject go)
{
if (go != null)
{
_trackGameObjects.Add(go);
AssetSystem.AddAutoReleaseGameObjectHandle(this);
}
}
internal void CheckAutoReleaseHandle()
{
if (IsValidNoWarning == false)
return;
if (_trackGameObjects.Count == 0)
return;
foreach (var go in _trackGameObjects)
{
if (go != null)
return;
}
ReleaseInternal();
}
#endregion
} }
} }

View File

@@ -4,13 +4,13 @@ namespace YooAsset
{ {
public abstract class OperationHandleBase : IEnumerator public abstract class OperationHandleBase : IEnumerator
{ {
private readonly string _cachedAssetPath; private readonly AssetInfo _assetInfo;
internal ProviderBase Provider { private set; get; } internal ProviderBase Provider { private set; get; }
internal OperationHandleBase(ProviderBase provider) internal OperationHandleBase(ProviderBase provider)
{ {
Provider = provider; Provider = provider;
_cachedAssetPath = provider.AssetPath; _assetInfo = provider.MainAssetInfo;
} }
internal abstract void InvokeCallback(); internal abstract void InvokeCallback();
@@ -85,14 +85,28 @@ namespace YooAsset
else else
{ {
if (Provider == null) if (Provider == null)
YooLogger.Warning($"Operation handle is released : {_cachedAssetPath}"); YooLogger.Warning($"Operation handle is released : {_assetInfo.AssetPath}");
else if (Provider.IsDestroyed) else if (Provider.IsDestroyed)
YooLogger.Warning($"Provider is destroyed : {_cachedAssetPath}"); YooLogger.Warning($"Provider is destroyed : {_assetInfo.AssetPath}");
return false; return false;
} }
} }
} }
/// <summary>
/// 句柄是否有效
/// </summary>
public bool IsValidNoWarning
{
get
{
if (Provider != null && Provider.IsDestroyed == false)
return true;
else
return false;
}
}
/// <summary> /// <summary>
/// 释放句柄 /// 释放句柄
/// </summary> /// </summary>

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