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.
## [1.1.0] - 2022-06-23
### Fixed
- 修复了AssetBundleCollector窗口在切换EnableAddressable时未及时刷新界面的问题。
- 修复了AssetBundleCollector窗口资源过滤器CollectSprite无效的问题。
- 修复了AssetBundleCollector窗口无法正常预览StaticAssetCollector的资源列表的问题。
- 修复了在离线模式下原生文件每次都从包内加载的问题。
### Changed
- 变更了共享资源打包机制。
- AssetBundleCollector窗口增加了分组禁用功能。
- AssetBundleDebugger窗口增加了真机远程调试功能。
- AssetBundleBuilder窗口在构建成功后自动显示构建文件夹。
- DownloaderOperation.OnDownloadFileFailedCallback委托变更为OnDownloadErrorCallback委托。
### Added
- 新增UpdateManifestOperation.FoundNewManifest字段。
- 新增DownloaderOperation.OnStartDownloadFileCallback委托。
- 新增AssetInfo.Address字段。
- 新增YooAssets.IsInitialized字段。
- 新增YooAssets初始化参数。
````c#
/// <summary>
/// 下载文件校验等级
/// </summary>
public EVerifyLevel VerifyLevel = EVerifyLevel.High;
````
- 新增YooAssets获取资源完成路径的方法。
````c#
/// <summary>
/// 获取资源路径
/// </summary>
/// <param name="location">资源的定位地址</param>
/// <returns>如果location地址无效则返回空字符串</returns>
public static string GetAssetPath(string location);
````
- 新增YooAssets初始化参数。
```c#
/// <summary>
/// 自动释放游戏对象所属资源句柄
/// 说明:通过资源句柄实例化的游戏对象在销毁之后,会自动释放所属资源句柄。
/// </summary>
public bool AutoReleaseGameObjectHandle = false;
```
## [1.0.10] - 2022-05-22
### Fixed
- 修复了资源收集配置存在多个的时候,导致后续无法打开窗口的问题。
- 修复了在编辑器模拟模式下加载精灵图片失败的问题。
- 修复了在Unity2019版本无法识别配置文件的问题。
### Changed
- 资源构建增加内置资源文件(首包资源文件)拷贝的选项。
- 补丁下载器增加暂停方法和恢复方法。
- 在资源收集界面对Collector的增加和删除支持撤销和恢复操作。
## [1.0.9] - 2022-05-14
### Fixed
- 修复了YooAssets.GetAssetInfos(string Tag)方法返回了无关的资源信息的问题。
### Changed
- 编辑器下的模拟运行模式,不再依赖配置里的构建版本。
- 更新资源清单结构,资源对象类增加分类标签。
- 优化了资源工具相关配置文件的加载方式和途径,这些配置文件可以放置在任何目录下。
- 优化了Location无效后的错误报告方式。
- 优化了资源包的构建参数现在始终开启DisableLoadAssetByFileName帮助减小运行时的内存。
- YooAssets.ProcessOperation()重命名为YooAssets.StartOperation()
### Added
- 新增YooAssets.IsNeedDownloadFromRemote()方法。
````c#
public static bool IsNeedDownloadFromRemote(string location);
````
- 新增获取所有子资源对象的方法。
````c#
class SubAssetsOperationHandle
{
public TObject[] GetSubAssetObjects<TObject>();
}
````
### Removed
- YooAssets.GetBundleInfo()方法已经移除。
## [1.0.8] - 2022-05-08
### Fixed
- 修复了资源收集器导出配置文件时没有导出公共设置。
- 修复了不兼容Unity2018版本的错误。
### Changed
- AssetBundleGrouper窗口变更为AssetBundleCollector窗口。
- **优化了编辑器下模拟运行的初始化速度**。
- **优化了资源收集窗口打开时卡顿的问题**。
- 资源收集XML配表支持版本兼容。
- 资源报告查看窗口支持预览AssetBundle文件内容的功能。
- 完善了对UniTask的支持。
- YooAssets所有接口支持初始化容错检测。
### Added
- 异步操作类增加进度查询字段。
```c#
class AsyncOperationBase
{
/// <summary>
/// 处理进度
/// </summary>
public float Progress { get; protected set; }
}
```
- 增加开启异步操作的方法。
```c#
/// <summary>
/// 开启一个异步操作
/// </summary>
/// <param name="operation">异步操作对象</param>
public static void ProcessOperaiton(GameAsyncOperation operation)
```
- 新增编辑器下模拟模式的初始化参数。
````c#
/// <summary>
/// 用于模拟运行的资源清单路径
/// 注意:如果路径为空,会自动重新构建补丁清单。
/// </summary>
public string SimulatePatchManifestPath;
````
- 新增通用的初始化参数。
```c#
/// <summary>
/// 资源定位地址大小写不敏感
/// </summary>
public bool LocationToLower = false;
```
## [1.0.7] - 2022-05-04
### Fixed

View File

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

View File

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

View File

@@ -24,22 +24,7 @@ namespace YooAsset.Editor
/// </summary>
private static void LoadSettingData()
{
// 加载配置文件
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");
}
_setting = EditorHelper.LoadSettingData<AssetBundleBuilderSetting>();
}
/// <summary>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,38 +12,46 @@ namespace YooAsset.Editor
{
var buildParameters = context.GetContextObject<AssetBundleBuilder.BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
CreateReportFile(buildParameters, buildMapContext);
buildParameters.StopWatch();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild)
{
CreateReportFile(buildParameters, buildMapContext);
}
else
{
float buildSeconds = buildParameters.GetBuildingSeconds();
BuildRunner.Info($"Build time consuming {buildSeconds} seconds.");
}
}
private void CreateReportFile(AssetBundleBuilder.BuildParametersContext buildParameters, BuildMapContext buildMapContext)
{
PatchManifest patchManifest = AssetBundleBuilderHelper.LoadPatchManifestFile(buildParameters.PipelineOutputDirectory, buildParameters.Parameters.BuildVersion);
BuildReport buildReport = new BuildReport();
buildParameters.StopWatch();
BuildReport buildReport = new BuildReport();
// 概述信息
{
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildTime = DateTime.Now.ToString();
buildReport.Summary.BuildSeconds = buildParameters.GetBuildingSeconds();
buildReport.Summary.BuildSeconds = (int)buildParameters.GetBuildingSeconds();
buildReport.Summary.BuildTarget = buildParameters.Parameters.BuildTarget;
buildReport.Summary.BuildMode = buildParameters.Parameters.BuildMode;
buildReport.Summary.BuildVersion = buildParameters.Parameters.BuildVersion;
buildReport.Summary.BuildinTags = buildParameters.Parameters.BuildinTags;
buildReport.Summary.EnableAddressable = buildParameters.Parameters.EnableAddressable;
buildReport.Summary.EnableAutoCollect = buildParameters.Parameters.EnableAutoCollect;
buildReport.Summary.AppendFileExtension = buildParameters.Parameters.AppendFileExtension;
buildReport.Summary.AutoCollectShaders = AssetBundleGrouperSettingData.Setting.AutoCollectShaders;
buildReport.Summary.ShadersBundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName;
buildReport.Summary.CopyBuildinTagFiles = buildParameters.Parameters.CopyBuildinTagFiles;
buildReport.Summary.AutoCollectShaders = AssetBundleCollectorSettingData.Setting.AutoCollectShaders;
buildReport.Summary.ShadersBundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
buildReport.Summary.EncryptionServicesClassName = buildParameters.Parameters.EncryptionServices == null ?
"null" : buildParameters.Parameters.EncryptionServices.GetType().FullName;
// 构建参数
buildReport.Summary.CompressOption = buildParameters.Parameters.CompressOption;
buildReport.Summary.AppendHash = buildParameters.Parameters.AppendHash;
buildReport.Summary.DisableWriteTypeTree = buildParameters.Parameters.DisableWriteTypeTree;
buildReport.Summary.IgnoreTypeTreeChanges = buildParameters.Parameters.IgnoreTypeTreeChanges;
buildReport.Summary.DisableLoadAssetByFileName = buildParameters.Parameters.DisableLoadAssetByFileName;
// 构建结果
buildReport.Summary.AssetFileTotalCount = buildMapContext.AssetFileCount;
@@ -65,6 +73,7 @@ namespace YooAsset.Editor
ReportAssetInfo reportAssetInfo = new ReportAssetInfo();
reportAssetInfo.Address = patchAsset.Address;
reportAssetInfo.AssetPath = patchAsset.AssetPath;
reportAssetInfo.AssetTags = patchAsset.AssetTags;
reportAssetInfo.AssetGUID = AssetDatabase.AssetPathToGUID(patchAsset.AssetPath);
reportAssetInfo.MainBundleName = mainBundle.BundleName;
reportAssetInfo.MainBundleSize = mainBundle.SizeBytes;

View File

@@ -12,7 +12,8 @@ namespace YooAsset.Editor
{
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);
BuildRunner.Log("构建内容准备完毕!");

View File

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

View File

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

View File

@@ -51,13 +51,13 @@ namespace YooAsset.Editor
if (CollectorType == ECollectorType.None)
return false;
if (AssetBundleGrouperSettingData.HasAddressRuleName(AddressRuleName) == false)
if (AssetBundleCollectorSettingData.HasAddressRuleName(AddressRuleName) == false)
return false;
if (AssetBundleGrouperSettingData.HasPackRuleName(PackRuleName) == false)
if (AssetBundleCollectorSettingData.HasPackRuleName(PackRuleName) == false)
return false;
if (AssetBundleGrouperSettingData.HasFilterRuleName(FilterRuleName) == false)
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
return false;
return true;
@@ -74,21 +74,28 @@ namespace YooAsset.Editor
if (CollectorType == ECollectorType.None)
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}");
if (AssetBundleGrouperSettingData.HasFilterRuleName(FilterRuleName) == false)
if (AssetBundleCollectorSettingData.HasFilterRuleName(FilterRuleName) == false)
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}");
}
/// <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);
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}");
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))
@@ -110,7 +117,7 @@ namespace YooAsset.Editor
{
if (result.ContainsKey(assetPath) == false)
{
var collectAssetInfo = CreateCollectAssetInfo(grouper, assetPath, isRawAsset);
var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo);
}
else
@@ -125,7 +132,7 @@ namespace YooAsset.Editor
string assetPath = CollectPath;
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
{
var collectAssetInfo = CreateCollectAssetInfo(grouper, assetPath, isRawAsset);
var collectAssetInfo = CreateCollectAssetInfo(buildMode, group, assetPath, isRawAsset);
result.Add(assetPath, collectAssetInfo);
}
else
@@ -135,7 +142,7 @@ namespace YooAsset.Editor
}
// 检测可寻址地址是否重复
if (AssetBundleGrouperSettingData.Setting.EnableAddressable)
if (AssetBundleCollectorSettingData.Setting.EnableAddressable)
{
HashSet<string> adressTemper = new HashSet<string>();
foreach (var collectInfoPair in result)
@@ -155,13 +162,19 @@ namespace YooAsset.Editor
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 bundleName = GetBundleName(grouper, assetPath);
List<string> assetTags = GetAssetTags(grouper);
string address = GetAddress(group, assetPath);
string bundleName = GetBundleName(group, assetPath);
List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, assetTags, isRawAsset);
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
// 注意:模拟构建模式下不需要收集依赖资源
if (buildMode == EBuildMode.SimulateBuild)
collectAssetInfo.DependAssets = new List<string>();
else
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
return collectAssetInfo;
}
private bool IsValidateAsset(string assetPath)
@@ -186,7 +199,7 @@ namespace YooAsset.Editor
private bool IsCollectAsset(string assetPath)
{
// 如果收集全路径着色器
if (AssetBundleGrouperSettingData.Setting.AutoCollectShaders)
if (AssetBundleCollectorSettingData.Setting.AutoCollectShaders)
{
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
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));
}
private string GetAddress(AssetBundleGrouper grouper, string assetPath)
private string GetAddress(AssetBundleCollectorGroup group, string assetPath)
{
if (CollectorType != ECollectorType.MainAssetCollector)
return string.Empty;
IAddressRule addressRuleInstance = AssetBundleGrouperSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, grouper.GrouperName));
IAddressRule addressRuleInstance = AssetBundleCollectorSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName));
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);
if (assetType == typeof(UnityEngine.Shader))
{
string bundleName = AssetBundleGrouperSettingData.Setting.ShadersBundleName;
string bundleName = AssetBundleCollectorSettingData.Setting.ShadersBundleName;
return EditorTools.GetRegularPath(bundleName).ToLower();
}
}
// 根据规则设置获取资源包名称
{
IPackRule packRuleInstance = AssetBundleGrouperSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, grouper.GrouperName));
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName));
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, ';');
tags.AddRange(temper);
return tags;

View File

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

View File

@@ -8,23 +8,28 @@ using UnityEditor;
namespace YooAsset.Editor
{
[Serializable]
public class AssetBundleGrouper
public class AssetBundleCollectorGroup
{
/// <summary>
/// 分组名称
/// </summary>
public string GrouperName = string.Empty;
public string GroupName = string.Empty;
/// <summary>
/// 分组描述
/// </summary>
public string GrouperDesc = string.Empty;
public string GroupDesc = string.Empty;
/// <summary>
/// 资源分类标签
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 分组激活规则
/// </summary>
public string ActiveRuleName = nameof(EnableGroup);
/// <summary>
/// 分组的收集器列表
/// </summary>
@@ -36,6 +41,9 @@ namespace YooAsset.Editor
/// </summary>
public void CheckConfigError()
{
if (AssetBundleCollectorSettingData.HasActiveRuleName(ActiveRuleName) == false)
throw new Exception($"Invalid {nameof(IActiveRule)} class type : {ActiveRuleName} in group : {GroupName}");
foreach (var collector in Collectors)
{
collector.CheckConfigError();
@@ -45,25 +53,32 @@ namespace YooAsset.Editor
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets()
public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(10000);
// 检测分组是否激活
IActiveRule activeRule = AssetBundleCollectorSettingData.GetActiveRuleInstance(ActiveRuleName);
if (activeRule.IsActiveGroup() == false)
{
return new List<CollectAssetInfo>();
}
// 收集打包资源
foreach (var collector in Collectors)
{
var temper = collector.GetAllCollectAssets(this);
var temper = collector.GetAllCollectAssets(buildMode, this);
foreach (var assetInfo in temper)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in 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>();
foreach (var collectInfoPair in result)
@@ -74,7 +89,7 @@ namespace YooAsset.Editor
if (adressTemper.Contains(address) == false)
adressTemper.Add(address);
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
{
public class AssetBundleGrouperSetting : ScriptableObject
public class AssetBundleCollectorSetting : ScriptableObject
{
/// <summary>
/// 是否启用可寻址资源定位
@@ -26,7 +26,7 @@ namespace YooAsset.Editor
/// <summary>
/// 分组列表
/// </summary>
public List<AssetBundleGrouper> Groupers = new List<AssetBundleGrouper>();
public List<AssetBundleCollectorGroup> Groups = new List<AssetBundleCollectorGroup>();
/// <summary>
@@ -34,29 +34,29 @@ namespace YooAsset.Editor
/// </summary>
public void CheckConfigError()
{
foreach (var grouper in Groupers)
foreach (var group in Groups)
{
grouper.CheckConfigError();
group.CheckConfigError();
}
}
/// <summary>
/// 获取打包收集的资源文件
/// </summary>
public List<CollectAssetInfo> GetAllCollectAssets()
public List<CollectAssetInfo> GetAllCollectAssets(EBuildMode buildMode)
{
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)
{
if (result.ContainsKey(assetInfo.AssetPath) == false)
result.Add(assetInfo.AssetPath, assetInfo);
else
throw new Exception($"The collecting asset file is existed : {assetInfo.AssetPath} in grouper 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)
adressTemper.Add(address);
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
{
public class AssetBundleGrouperSettingData
public class AssetBundleCollectorSettingData
{
private static readonly Dictionary<string, System.Type> _cacheActiveRuleTypes = new Dictionary<string, Type>();
private static readonly Dictionary<string, IActiveRule> _cacheActiveRuleInstance = new Dictionary<string, IActiveRule>();
private static readonly Dictionary<string, System.Type> _cacheAddressRuleTypes = new Dictionary<string, System.Type>();
private static readonly Dictionary<string, IAddressRule> _cacheAddressRuleInstance = new Dictionary<string, IAddressRule>();
@@ -24,8 +27,8 @@ namespace YooAsset.Editor
public static bool IsDirty { private set; get; } = false;
private static AssetBundleGrouperSetting _setting = null;
public static AssetBundleGrouperSetting Setting
private static AssetBundleCollectorSetting _setting = null;
public static AssetBundleCollectorSetting Setting
{
get
{
@@ -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()
{
if (_setting == null)
@@ -71,6 +86,15 @@ namespace YooAsset.Editor
}
return names;
}
public static bool HasActiveRuleName(string ruleName)
{
foreach (var pair in _cacheActiveRuleTypes)
{
if (pair.Key == ruleName)
return true;
}
return false;
}
public static bool HasAddressRuleName(string ruleName)
{
foreach (var pair in _cacheAddressRuleTypes)
@@ -105,22 +129,7 @@ namespace YooAsset.Editor
/// </summary>
private static void LoadSettingData()
{
// 加载配置文件
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");
}
_setting = EditorHelper.LoadSettingData<AssetBundleCollectorSetting>();
// IPackRule
{
@@ -135,12 +144,11 @@ namespace YooAsset.Editor
typeof(PackDirectory),
typeof(PackTopDirectory),
typeof(PackCollector),
typeof(PackGrouper),
typeof(PackGroup),
typeof(PackRawFile),
};
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IPackRule>();
var customTypes = collection.ToList();
var customTypes = EditorTools.GetAssignableTypes(typeof(IPackRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
@@ -165,8 +173,7 @@ namespace YooAsset.Editor
typeof(CollectSprite)
};
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IFilterRule>();
var customTypes = collection.ToList();
var customTypes = EditorTools.GetAssignableTypes(typeof(IFilterRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
@@ -187,11 +194,10 @@ namespace YooAsset.Editor
{
typeof(AddressByFileName),
typeof(AddressByCollectorAndFileName),
typeof(AddressByGrouperAndFileName)
typeof(AddressByGroupAndFileName)
};
TypeCache.TypeCollection collection = TypeCache.GetTypesDerivedFrom<IAddressRule>();
var customTypes = collection.ToList();
var customTypes = EditorTools.GetAssignableTypes(typeof(IAddressRule));
types.AddRange(customTypes);
for (int i = 0; i < types.Count; i++)
{
@@ -200,6 +206,29 @@ namespace YooAsset.Editor
_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>
@@ -212,7 +241,7 @@ namespace YooAsset.Editor
IsDirty = false;
EditorUtility.SetDirty(Setting);
AssetDatabase.SaveAssets();
Debug.Log($"{nameof(AssetBundleGrouperSetting)}.asset is saved!");
Debug.Log($"{nameof(AssetBundleCollectorSetting)}.asset is saved!");
}
}
@@ -223,11 +252,28 @@ namespace YooAsset.Editor
{
Setting.AutoCollectShaders = false;
Setting.ShadersBundleName = string.Empty;
Setting.Groupers.Clear();
Setting.Groups.Clear();
SaveFile();
}
// 实例类相关
public static IActiveRule GetActiveRuleInstance(string ruleName)
{
if (_cacheActiveRuleInstance.TryGetValue(ruleName, out IActiveRule instance))
return instance;
// 如果不存在创建类的实例
if (_cacheActiveRuleTypes.TryGetValue(ruleName, out Type type))
{
instance = (IActiveRule)Activator.CreateInstance(type);
_cacheActiveRuleInstance.Add(ruleName, instance);
return instance;
}
else
{
throw new Exception($"{nameof(IActiveRule)}类型无效:{ruleName}");
}
}
public static IAddressRule GetAddressRuleInstance(string ruleName)
{
if (_cacheAddressRuleInstance.TryGetValue(ruleName, out IAddressRule instance))
@@ -296,43 +342,43 @@ namespace YooAsset.Editor
}
// 资源分组编辑相关
public static void CreateGrouper(string grouperName)
public static void CreateGroup(string groupName)
{
AssetBundleGrouper grouper = new AssetBundleGrouper();
grouper.GrouperName = grouperName;
Setting.Groupers.Add(grouper);
AssetBundleCollectorGroup group = new AssetBundleCollectorGroup();
group.GroupName = groupName;
Setting.Groups.Add(group);
IsDirty = true;
}
public static void RemoveGrouper(AssetBundleGrouper grouper)
public static void RemoveGroup(AssetBundleCollectorGroup group)
{
if (Setting.Groupers.Remove(grouper))
if (Setting.Groups.Remove(group))
{
IsDirty = true;
}
else
{
Debug.LogWarning($"Failed remove grouper : {grouper.GrouperName}");
Debug.LogWarning($"Failed remove group : {group.GroupName}");
}
}
public static void ModifyGrouper(AssetBundleGrouper grouper)
public static void ModifyGroup(AssetBundleCollectorGroup group)
{
if (grouper != null)
if (group != null)
{
IsDirty = true;
}
}
// 资源收集器编辑相关
public static void CreateCollector(AssetBundleGrouper grouper, string collectPath)
public static void CreateCollector(AssetBundleCollectorGroup group, string collectPath)
{
AssetBundleCollector collector = new AssetBundleCollector();
collector.CollectPath = collectPath;
grouper.Collectors.Add(collector);
group.Collectors.Add(collector);
IsDirty = true;
}
public static void RemoveCollector(AssetBundleGrouper grouper, AssetBundleCollector collector)
public static void RemoveCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (grouper.Collectors.Remove(collector))
if (group.Collectors.Remove(collector))
{
IsDirty = true;
}
@@ -341,9 +387,9 @@ namespace YooAsset.Editor
Debug.LogWarning($"Failed remove collector : {collector.CollectPath}");
}
}
public static void ModifyCollector(AssetBundleGrouper grouper, AssetBundleCollector collector)
public static void ModifyCollector(AssetBundleCollectorGroup group, AssetBundleCollector collector)
{
if (grouper != null && collector != null)
if (group != null && collector != null)
{
IsDirty = true;
}

View File

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

View File

@@ -5,8 +5,8 @@
</uie:Toolbar>
<ui:VisualElement name="ContentContainer" style="flex-grow: 1; flex-direction: row;">
<ui:VisualElement name="LeftContainer" style="width: 200px; flex-grow: 0; background-color: rgb(67, 67, 67); border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:ListView focusable="true" name="GrouperListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="GrouperAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:ListView focusable="true" name="GroupListView" item-height="20" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:VisualElement name="GroupAddContainer" style="height: 20px; flex-direction: row; justify-content: center;">
<ui:Button text=" - " display-tooltip-when-elided="true" name="RemoveBtn" />
<ui:Button text=" + " display-tooltip-when-elided="true" name="AddBtn" />
</ui:VisualElement>
@@ -17,10 +17,11 @@
<ui:Toggle label="Auto Collect Shaders" name="AutoCollectShader" style="width: 196px; -unity-text-align: middle-left;" />
<ui:TextField picking-mode="Ignore" label="Shader Bundle Name" name="ShaderBundleName" style="flex-grow: 1; -unity-text-align: middle-left;" />
</ui:VisualElement>
<ui:VisualElement name="GrouperContainer" style="flex-grow: 1; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:TextField picking-mode="Ignore" label="Grouper Name" name="GrouperName" />
<ui:TextField picking-mode="Ignore" label="Grouper Desc" name="GrouperDesc" />
<ui:TextField picking-mode="Ignore" label="Grouper Asset Tags" name="GrouperAssetTags" />
<ui:VisualElement name="GroupContainer" style="flex-grow: 1; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:VisualElement name="ActiveRuleContainer" style="height: 20px;" />
<ui:TextField picking-mode="Ignore" label="Group Name" name="GroupName" />
<ui:TextField picking-mode="Ignore" label="Group Desc" name="GroupDesc" />
<ui:TextField picking-mode="Ignore" label="Group Asset Tags" name="GroupAssetTags" />
<ui:VisualElement name="CollectorAddContainer" style="height: 20px; flex-direction: row-reverse;">
<ui:Button text="[ + ]" display-tooltip-when-elided="true" name="AddBtn" />
</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>
public class AddressByGrouperAndFileName : IAddressRule
public class AddressByGroupAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
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)
{
if (AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath) == typeof(Sprite))
return true;
var mainAssetType = AssetDatabase.GetMainAssetTypeAtPath(data.AssetPath);
if(mainAssetType == typeof(Texture2D))
{
var texImporter = AssetImporter.GetAtPath(data.AssetPath) as TextureImporter;
if (texImporter != null && texImporter.textureType == TextureImporterType.Sprite)
return true;
else
return false;
}
else
{
return false;
}
}
}
}

View File

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

View File

@@ -0,0 +1,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 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;
CollectPath = collectPath;
GrouperName = grouperName;
GroupName = groupName;
}
}

View File

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

View File

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

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">
<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: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;" />

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ using UnityEngine.UIElements;
namespace YooAsset.Editor
{
internal class SummaryReporterViewer
internal class ReporterSummaryViewer
{
private class ItemWrapper
{
@@ -37,14 +37,10 @@ namespace YooAsset.Editor
public void InitViewer()
{
// 加载布局文件
string rootPath = EditorTools.GetYooAssetSourcePath();
string uxml = $"{rootPath}/Editor/AssetBundleReporter/VisualViewers/{nameof(SummaryReporterViewer)}.uxml";
_visualAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(uxml);
_visualAsset = EditorHelper.LoadWindowUXML<ReporterSummaryViewer>();
if (_visualAsset == null)
{
Debug.LogError($"Not found {nameof(SummaryReporterViewer)}.uxml : {uxml}");
return;
}
_root = _visualAsset.CloneTree();
_root.style.flexGrow = 1f;
@@ -71,8 +67,8 @@ namespace YooAsset.Editor
_items.Add(new ItemWrapper("内置资源标签", $"{buildReport.Summary.BuildinTags}"));
_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.CopyBuildinTagFiles}"));
_items.Add(new ItemWrapper("自动收集着色器", $"{buildReport.Summary.AutoCollectShaders}"));
_items.Add(new ItemWrapper("着色器资源包名称", $"{buildReport.Summary.ShadersBundleName}"));
_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));
_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("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));

View File

@@ -4,10 +4,12 @@ namespace YooAsset.Editor
{
public class EditorDefine
{
#if UNITY_2019_4_OR_NEWER
/// <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>

View File

@@ -1,6 +1,7 @@

namespace YooAsset.Editor
{
#if UNITY_2019
public static partial class UnityEngine_UIElements_ListView_Extension
{
@@ -20,4 +21,5 @@ namespace YooAsset.Editor
}
}
#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.Reflection;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor;
@@ -15,7 +15,57 @@ namespace YooAsset.Editor
/// </summary>
public static class EditorTools
{
static EditorTools()
{
InitAssembly();
}
#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>
@@ -190,7 +240,7 @@ namespace YooAsset.Editor
}
#endregion
#region
#region EditorConsole
private static MethodInfo _clearConsoleMethod;
private static MethodInfo ClearConsoleMethod
{
@@ -412,9 +462,6 @@ namespace YooAsset.Editor
#endregion
#region
private static string YooAssetSourcePath;
private static string YooAssetSettingPath;
/// <summary>
/// 获取规范的路径
/// </summary>
@@ -423,83 +470,6 @@ namespace YooAsset.Editor
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>
@@ -516,7 +486,7 @@ namespace YooAsset.Editor
public static string AbsolutePathToAssetPath(string absolutePath)
{
string content = GetRegularPath(absolutePath);
return Substring(content, "Assets", true);
return Substring(content, "Assets/", true);
}
/// <summary>
@@ -551,40 +521,6 @@ namespace YooAsset.Editor
}
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>
/// 截取字符串
@@ -594,7 +530,7 @@ namespace YooAsset.Editor
/// <param name="key">关键字</param>
/// <param name="includeKey">分割的结果里是否包含关键字</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))
return content;

View File

@@ -98,7 +98,7 @@ namespace YooAsset.Editor
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();
foreach (var assetPath in collectAssets)
{

View File

@@ -25,22 +25,7 @@ namespace YooAsset.Editor
/// </summary>
private static void LoadSettingData()
{
// 加载配置文件
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");
}
_setting = EditorHelper.LoadSettingData<ShaderVariantCollectorSetting>();
}
/// <summary>

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
@@ -11,36 +10,31 @@ namespace YooAsset
{
private static readonly List<AssetBundleLoaderBase> _loaders = new List<AssetBundleLoaderBase>(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);
/// <summary>
/// 在编辑器下模拟运行
/// </summary>
public static bool SimulationOnEditor { private set; get; }
/// <summary>
/// 运行时的最大加载个数
/// </summary>
public static int AssetLoadingMaxNumber { private set; get; }
private static bool _simulationOnEditor;
private static int _loadingMaxNumber;
public static bool AutoReleaseGameObjectHandle { private set; get; }
public static IDecryptionServices DecryptionServices { private set; get; }
public static IBundleServices BundleServices { private set; get; }
/// <summary>
/// 初始化资源系统
/// 初始化
/// 注意在使用AssetSystem之前需要初始化
/// </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;
AssetLoadingMaxNumber = assetLoadingMaxNumber;
_simulationOnEditor = simulationOnEditor;
_loadingMaxNumber = loadingMaxNumber;
AutoReleaseGameObjectHandle = autoReleaseGameObjectHandle;
DecryptionServices = decryptionServices;
BundleServices = bundleServices;
}
/// <summary>
/// 轮询更新
/// 更新
/// </summary>
public static void Update()
{
@@ -63,7 +57,7 @@ namespace YooAsset
}
else
{
if (loadingCount < AssetLoadingMaxNumber)
if (loadingCount < _loadingMaxNumber)
provider.Update();
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>
public static void UnloadUnusedAssets()
{
if (SimulationOnEditor)
if (AutoReleaseGameObjectHandle)
{
CheckAutoReleaseGameObjectHandle();
}
if (_simulationOnEditor)
{
for (int i = _providers.Count - 1; i >= 0; i--)
{
@@ -128,15 +140,22 @@ namespace YooAsset
Resources.UnloadUnusedAssets();
}
/// <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))
return _sceneHandles[scenePath];
string providerGUID = assetInfo.ProviderGUID;
if (_sceneHandles.ContainsKey(providerGUID))
return _sceneHandles[providerGUID];
// 如果加载的是主场景,则卸载所有缓存的场景
if (sceneMode == LoadSceneMode.Single)
@@ -144,68 +163,104 @@ namespace YooAsset
UnloadAllScene();
}
ProviderBase provider = TryGetProvider(scenePath);
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
if (SimulationOnEditor)
provider = new DatabaseSceneProvider(scenePath, sceneMode, activateOnLoad, priority);
if (_simulationOnEditor)
provider = new DatabaseSceneProvider(assetInfo, sceneMode, activateOnLoad, priority);
else
provider = new BundledSceneProvider(scenePath, sceneMode, activateOnLoad, priority);
provider = new BundledSceneProvider(assetInfo, sceneMode, activateOnLoad, priority);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
}
var handle = provider.CreateHandle() as SceneOperationHandle;
_sceneHandles.Add(scenePath, handle);
var handle = provider.CreateHandle<SceneOperationHandle>();
_sceneHandles.Add(providerGUID, handle);
return handle;
}
/// <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 (SimulationOnEditor)
provider = new DatabaseAssetProvider(assetPath, assetType);
if (_simulationOnEditor)
provider = new DatabaseAssetProvider(assetInfo);
else
provider = new BundledAssetProvider(assetPath, assetType);
provider = new BundledAssetProvider(assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
}
return provider.CreateHandle() as AssetOperationHandle;
return provider.CreateHandle<AssetOperationHandle>();
}
/// <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 (SimulationOnEditor)
provider = new DatabaseSubAssetsProvider(assetPath, assetType);
if (_simulationOnEditor)
provider = new DatabaseSubAssetsProvider(assetInfo);
else
provider = new BundledSubAssetsProvider(assetPath, assetType);
provider = new BundledSubAssetsProvider(assetInfo);
provider.InitSpawnDebugInfo();
_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)
{
string scenePath = provider.AssetPath;
if (_sceneHandles.ContainsKey(scenePath) == false)
string providerGUID = provider.MainAssetInfo.ProviderGUID;
if (_sceneHandles.ContainsKey(providerGUID) == false)
throw new Exception("Should never get here !");
// 释放子场景句柄
_sceneHandles[scenePath].ReleaseInternal();
_sceneHandles.Remove(scenePath);
_sceneHandles[providerGUID].ReleaseInternal();
_sceneHandles.Remove(providerGUID);
// 卸载未被使用的资源(包括场景)
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(bundleName);
BundleInfo bundleInfo = BundleServices.GetBundleInfo(assetInfo);
return CreateAssetBundleLoaderInternal(bundleInfo);
}
internal static List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(string assetPath)
internal static List<AssetBundleLoaderBase> CreateDependAssetBundleLoaders(AssetInfo assetInfo)
{
List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>();
string[] depends = BundleServices.GetAllDependencies(assetPath);
if (depends != null)
BundleInfo[] depends = BundleServices.GetAllDependBundleInfos(assetInfo);
List<AssetBundleLoaderBase> result = new List<AssetBundleLoaderBase>(depends.Length);
foreach (var bundleInfo in depends)
{
foreach (var dependBundleName in depends)
{
BundleInfo dependBundleInfo = BundleServices.GetBundleInfo(dependBundleName);
AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(dependBundleInfo);
result.Add(dependLoader);
}
AssetBundleLoaderBase dependLoader = CreateAssetBundleLoaderInternal(bundleInfo);
result.Add(dependLoader);
}
return result;
}
@@ -291,7 +341,7 @@ namespace YooAsset
for (int i = 0; i < _loaders.Count; i++)
{
AssetBundleLoaderBase temp = _loaders[i];
if (temp.BundleFileInfo.BundleName.Equals(bundleName))
if (temp.MainBundleInfo.BundleName.Equals(bundleName))
{
loader = temp;
break;
@@ -299,13 +349,13 @@ namespace YooAsset
}
return loader;
}
private static ProviderBase TryGetProvider(string assetPath)
private static ProviderBase TryGetProvider(string providerGUID)
{
ProviderBase provider = null;
for (int i = 0; i < _providers.Count; i++)
{
ProviderBase temp = _providers[i];
if (temp.AssetPath.Equals(assetPath))
if (temp.MainAssetInfo.ProviderGUID.Equals(providerGUID))
{
provider = temp;
break;
@@ -314,23 +364,23 @@ namespace YooAsset
return provider;
}
#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.AssetCount = _providers.Count;
foreach (var provider in _providers)
{
DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.AssetPath = provider.AssetPath;
providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
providerInfo.SpawnScene = provider.SpawnScene;
providerInfo.SpawnTime = provider.SpawnTime;
providerInfo.RefCount = provider.RefCount;
providerInfo.Status = provider.Status;
providerInfo.BundleInfos.Clear();
providerInfo.Status = (int)provider.Status;
providerInfo.BundleInfos = new List<DebugBundleInfo>();
report.ProviderInfos.Add(providerInfo);
if (provider is BundledProvider)
@@ -342,6 +392,7 @@ namespace YooAsset
// 重新排序
report.ProviderInfos.Sort();
return report;
}
#endregion
}

View File

@@ -1,4 +1,5 @@
using UnityEngine;
using System.Collections.Generic;
namespace YooAsset
{
@@ -117,26 +118,72 @@ namespace YooAsset
if (Provider.AssetObject == null)
return null;
GameObject result;
if (setPositionRotation)
{
if (parent == null)
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation);
result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation);
else
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation, parent);
result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject, position, rotation, parent);
}
else
{
if (parent == null)
return UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject);
result = UnityEngine.Object.Instantiate(Provider.AssetObject as GameObject);
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)
{
InstantiateOperation operation = new InstantiateOperation(this, position, rotation, parent, setPositionRotation);
OperationSystem.ProcessOperaiton(operation);
OperationSystem.StartOperaiton(operation);
if (AssetSystem.AutoReleaseGameObjectHandle)
{
operation.Completed += InstantiateOperationCompleted;
}
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
{
private readonly string _cachedAssetPath;
private readonly AssetInfo _assetInfo;
internal ProviderBase Provider { private set; get; }
internal OperationHandleBase(ProviderBase provider)
{
Provider = provider;
_cachedAssetPath = provider.AssetPath;
_assetInfo = provider.MainAssetInfo;
}
internal abstract void InvokeCallback();
@@ -85,14 +85,28 @@ namespace YooAsset
else
{
if (Provider == null)
YooLogger.Warning($"Operation handle is released : {_cachedAssetPath}");
YooLogger.Warning($"Operation handle is released : {_assetInfo.AssetPath}");
else if (Provider.IsDestroyed)
YooLogger.Warning($"Provider is destroyed : {_cachedAssetPath}");
YooLogger.Warning($"Provider is destroyed : {_assetInfo.AssetPath}");
return false;
}
}
}
/// <summary>
/// 句柄是否有效
/// </summary>
public bool IsValidNoWarning
{
get
{
if (Provider != null && Provider.IsDestroyed == false)
return true;
else
return false;
}
}
/// <summary>
/// 释放句柄
/// </summary>

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