Compare commits

..

63 Commits

Author SHA1 Message Date
hevinci
39ffad6da6 Update CHANGELOG.md 2023-03-03 17:28:51 +08:00
hevinci
13924fca13 Update package.json 2023-03-03 17:28:42 +08:00
hevinci
438f006d1d update samples 2023-03-03 17:28:24 +08:00
hevinci
6fb5626230 Update document 2023-03-03 17:28:03 +08:00
hevinci
ab29069af5 update download system
下载文件验证支持多线程。
2023-03-03 16:12:17 +08:00
hevinci
fc3ed28eda update samples 2023-03-03 11:53:22 +08:00
hevinci
46c9110b85 update asset bundle builder 2023-03-03 11:51:48 +08:00
hevinci
06b033ed36 update asset system
优化了资源加载器查询逻辑。
2023-03-03 11:23:15 +08:00
hevinci
ab96f3f28c update cache system
优化缓存系统的存储目录结构。
2023-03-01 20:35:01 +08:00
hevinci
295238cbb6 update asset system
优化资源对象加载耗时统计逻辑。
2023-03-01 18:23:47 +08:00
hevinci
4f0f0e54ac update asset bundle collector
优化了资源收集界面,查看Collector主资源列表卡顿问题。
2023-03-01 11:03:52 +08:00
hevinci
a9a01b08dc update patch system 2023-03-01 10:50:38 +08:00
hevinci
c27a3e105c update asset bundle builder
修复SBP构建时,如果有原生文件导致报错的问题。
2023-02-28 19:21:13 +08:00
hevinci
3cfc084e62 update cache system 2023-02-28 19:17:05 +08:00
hevinci
7c1873e861 update asset bundle builder
修复在构建过程中发生异常后进度条未消失的问题。
2023-02-28 19:01:32 +08:00
hevinci
c57c313dbe update samples 2023-02-28 18:26:10 +08:00
hevinci
19cf9c0129 update download system
修复关闭编辑器时的报错。
2023-02-28 18:25:48 +08:00
hevinci
ebcb05cc55 update cache system
优化了缓存系统初始化逻辑,支持分帧获取所有缓存文件。
2023-02-28 18:25:27 +08:00
hevinci
7c4dbb1f38 update asset bundle builder 2023-02-27 19:10:56 +08:00
hevinci
091b46ccaf update samples 2023-02-27 19:02:24 +08:00
hevinci
4da2bf441f update shader variant collector
着色器变种收集界面增加单次照射数量的控制。
2023-02-27 19:02:16 +08:00
hevinci
365ed560f6 update asset bundle builder
优化资源包引用关系计算效率。
2023-02-27 18:11:51 +08:00
hevinci
bcf6372602 update download system 2023-02-24 19:45:05 +08:00
hevinci
a5e24be5d4 update asset bundle builder
修复资源包存在循环依赖的情况下打包卡死的问题。
2023-02-24 18:49:45 +08:00
hevinci
cdaf6f0dca update samples 2023-02-24 16:52:50 +08:00
何冠峰
e38d0bc6d0 Merge pull request #70 from HXiaoMing/feat-custom-download-request
feat(DownloadSystem):支持自定义下载请求
2023-02-24 15:58:44 +08:00
huanggongming
eb16ba8365 feat(DownloadSystem):支持自定义下载请求 2023-02-24 12:18:18 +08:00
hevinci
3beb4f53d6 Update document 2023-02-24 12:13:18 +08:00
hevinci
f8ba0c9753 update asset system
修复引用链无效的问题。
2023-02-24 12:12:44 +08:00
hevinci
0232e5adec Update document 2023-02-23 12:15:41 +08:00
hevinci
a0bc521903 Update CHANGELOG.md 2023-02-22 18:56:54 +08:00
hevinci
071a84d9ef Update package.json 2023-02-22 18:56:46 +08:00
hevinci
aa40b5336e update samples 2023-02-22 18:41:29 +08:00
hevinci
157402bb39 update asset bundle collector
收集界面增加用户自定义数据栏。
2023-02-22 18:41:12 +08:00
何冠峰
5a98a68c27 Merge pull request #62 from DumoeDss/main
[feat] 添加自定义Address规则与跨平台资源收集
2023-02-22 17:10:03 +08:00
hevinci
f6bc52fd59 update asset bundle builder 2023-02-22 17:02:28 +08:00
hevinci
d1f2712e5f update cache system
缓存系统支持后缀名存储方式
2023-02-22 16:46:36 +08:00
hevinci
8958317f61 update asset bundle builder 2023-02-22 15:41:10 +08:00
hevinci
fdf27cbc1a update runtime logic
补丁清单的资源包列表增加引用链
2023-02-22 15:41:01 +08:00
hevinci
26ffb829d0 update samples 2023-02-22 15:29:00 +08:00
hevinci
521e3e2587 update asset bundle builder 2023-02-21 14:52:16 +08:00
hevinci
17c6158478 update cache system
EVerifyLevel 新增Middle等级
2023-02-21 14:35:02 +08:00
hevinci
fa0dc48993 update asset bundle reporter 2023-02-21 11:57:17 +08:00
Sayo
826bdaab5c Merge branch 'tuyoogame:main' into main 2023-02-20 16:33:35 +08:00
hevinci
7d21da76fb update sample 2023-02-20 15:54:22 +08:00
hevinci
70465a49d7 Update document 2023-02-20 14:58:28 +08:00
hevinci
acca74dce7 Update CHANGELOG.md 2023-02-17 19:15:34 +08:00
hevinci
d8e7892ab7 Update package.json 2023-02-17 19:15:22 +08:00
hevinci
e887bf1fd7 fix #67
修复报告查看界面2021.3兼容性问题
2023-02-17 19:07:10 +08:00
hevinci
145ca936e7 update sample 2023-02-17 18:44:19 +08:00
hevinci
69c7a51215 update runtime logic 2023-02-17 18:43:39 +08:00
hevinci
c4875d4f80 optimize pack rule
接口变动:IPackRule
2023-02-17 18:41:27 +08:00
hevinci
eed3c9768b Update document 2023-02-16 20:10:50 +08:00
Sayo
2c650f2bdf Merge branch 'tuyoogame:main' into main 2023-02-15 22:57:24 +08:00
hevinci
71e8392359 update AssetBundleBuilder 2023-02-14 17:29:19 +08:00
Sayo
cfbf6e23ec Merge branch 'tuyoogame:main' into main 2023-02-14 15:14:06 +08:00
hevinci
9be5ec0f31 Update CHANGELOG.md 2023-02-14 11:49:35 +08:00
hevinci
a8a0c3831b Update package.json 2023-02-14 11:49:21 +08:00
hevinci
ef31d5a938 update asset system
修复资源加载代码逻辑错误。
2023-02-14 11:40:35 +08:00
hevinci
812db6dafe fix #65
修复构建逻辑代码错误。
2023-02-14 11:39:01 +08:00
Sayo
a64d485278 Merge branch 'tuyoogame:main' into main 2023-02-08 10:42:07 +08:00
Sayo
fbba2ddec9 Merge branch 'tuyoogame:main' into main 2023-02-07 11:47:51 +08:00
Sayo
6488e96127 [feat] 添加跨平台资源收集 2023-01-30 12:07:34 +08:00
117 changed files with 1951 additions and 700 deletions

View File

@@ -2,6 +2,113 @@
All notable changes to this package will be documented in this file.
## [1.4.7] - 2023-03-03
### Fixed
- 修复了在运行时资源引用链无效的问题。
- 修复了在构建过程中发生异常后进度条未消失的问题。
- 修复了使用SBP构建管线如果有原生文件会导致打包失败的问题。
### Changed
- 支持自定义下载请求
```c#
/// <summary>
/// 设置下载系统参数,自定义下载请求
/// </summary>
public static void SetDownloadSystemUnityWebRequest(DownloadRequestDelegate requestDelegate)
```
- 优化了打包时资源包引用关系计算的逻辑。
- 优化了缓存系统初始化逻辑,支持分帧获取所有缓存文件。
- 优化了缓存系统的存储目录结构,提高了文件夹查询速度。
- 优化了在资源收集界面点击查看Collector主资源列表卡顿问题。
- 优化了资源对象加载耗时统计的逻辑,现在更加准确了。
- 优化了资源加载器查询逻辑。
- 优化了资源下载系统,下载文件的验证支持了多线程。
- 着色器变种收集界面增加单次照射数量的控制。
## [1.4.6-preview] - 2023-02-22
### Changed
- EVerifyLevel新增Middle级别。
```c#
public enum EVerifyLevel
{
/// <summary>
/// 验证文件存在
/// </summary>
Low,
/// <summary>
/// 验证文件大小
/// </summary>
Middle,
/// <summary>
/// 验证文件大小和CRC
/// </summary>
High,
}
```
- 补丁清单的资源包列表新增引用链。
(解决复杂依赖关系下,错误卸载资源包的问题)
- 缓存系统支持后缀格式存储。
(解决原生文件没有后缀格式的问题)
- 收集界面增加用户自定义数据栏。
## [1.4.5-preview] - 2023-02-17
### Fixed
- (#67)修复了报告查看界面在Unity2021.3上的兼容性问题。
- (#66)修复了在Unity2021.3上编辑器模拟模式运行报错的问题。
### Changed
- 接口变更IPackRule
````c#
/// <summary>
/// 资源打包规则接口
/// </summary>
public interface IPackRule
{
/// <summary>
/// 获取打包规则结果
/// </summary>
PackRuleResult GetPackRuleResult(PackRuleData data);
/// <summary>
/// 是否为原生文件打包规则
/// </summary>
bool IsRawFilePackRule();
}
````
## [1.4.4-preview] - 2023-02-14
### Fixed
- (#65)修复了AssetBundle构建宏逻辑错误。
- 修复了AssetBundle加载宏逻辑错误。
## [1.4.3-preview] - 2023-02-10
全新的缓存系统!

View File

@@ -41,9 +41,9 @@ namespace YooAsset.Editor
// 是否显示LOG
if (buildParameters.BuildMode == EBuildMode.SimulateBuild)
BuildRunner.EnableLog = false;
BuildLogger.EnableLog = false;
else
BuildRunner.EnableLog = true;
BuildLogger.EnableLog = true;
// 创建构建节点
List<IBuildTask> pipeline;
@@ -54,6 +54,7 @@ namespace YooAsset.Editor
new TaskPrepare(), //前期准备工作
new TaskGetBuildMap(), //获取构建列表
new TaskBuilding(), //开始执行构建
new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult(), //验证构建结果
new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息
@@ -70,6 +71,7 @@ namespace YooAsset.Editor
new TaskPrepare(), //前期准备工作
new TaskGetBuildMap(), //获取构建列表
new TaskBuilding_SBP(), //开始执行构建
new TaskCopyRawFile(), //拷贝原生文件
new TaskVerifyBuildResult_SBP(), //验证构建结果
new TaskEncryption(), //加密资源文件
new TaskUpdateBuildInfo(), //更新构建信息

View File

@@ -60,7 +60,7 @@ namespace YooAsset.Editor
// 加密服务类
_encryptionServicesClassTypes = GetEncryptionServicesClassTypes();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.FullName).ToList();
_encryptionServicesClassNames = _encryptionServicesClassTypes.Select(t => t.Name).ToList();
// 输出目录
string defaultOutputRoot = AssetBundleBuilderHelper.GetDefaultOutputRoot();

View File

@@ -7,8 +7,6 @@ namespace YooAsset.Editor
{
public class BuildAssetInfo
{
private string _mainBundleName;
private string _shareBundleName;
private bool _isAddAssetTags = false;
private readonly HashSet<string> _referenceBundleNames = new HashSet<string>();
@@ -17,6 +15,11 @@ namespace YooAsset.Editor
/// </summary>
public ECollectorType CollectorType { private set; get; }
/// <summary>
/// 资源包完整名称
/// </summary>
public string BundleName { private set; get; }
/// <summary>
/// 可寻址地址
/// </summary>
@@ -54,10 +57,10 @@ namespace YooAsset.Editor
public List<BuildAssetInfo> AllDependAssetInfos { private set; get; }
public BuildAssetInfo(ECollectorType collectorType, string mainBundleName, string address, string assetPath, bool isRawAsset)
public BuildAssetInfo(ECollectorType collectorType, string bundleName, string address, string assetPath, bool isRawAsset)
{
_mainBundleName = mainBundleName;
CollectorType = collectorType;
BundleName = bundleName;
Address = address;
AssetPath = assetPath;
IsRawAsset = isRawAsset;
@@ -133,24 +136,12 @@ namespace YooAsset.Editor
/// </summary>
public bool HasBundleName()
{
string bundleName = GetBundleName();
if (string.IsNullOrEmpty(bundleName))
if (string.IsNullOrEmpty(BundleName))
return false;
else
return true;
}
/// <summary>
/// 获取资源包名称
/// </summary>
public string GetBundleName()
{
if (CollectorType == ECollectorType.None)
return _shareBundleName;
else
return _mainBundleName;
}
/// <summary>
/// 添加关联的资源包名称
/// </summary>
@@ -164,53 +155,32 @@ namespace YooAsset.Editor
}
/// <summary>
/// 计算主资源或共享资源的完整包名
/// 计算共享资源的完整包名
/// </summary>
public void CalculateFullBundleName(bool uniqueBundleName, string packageName)
public void CalculateShareBundleName(bool uniqueBundleName, string packageName, string shadersBundleName)
{
if (CollectorType == ECollectorType.None)
if (CollectorType != ECollectorType.None)
return;
if (IsRawAsset)
throw new Exception("Should never get here !");
if (IsShaderAsset)
{
if (IsRawAsset)
throw new Exception("Should never get here !");
if (IsShaderAsset)
{
_shareBundleName = YooAssetSettingsData.GetUnityShadersBundleFullName(uniqueBundleName, packageName);
}
else
{
if (_referenceBundleNames.Count > 1)
{
IPackRule packRule = PackDirectory.StaticPackRule;
var bundleName = packRule.GetBundleName(new PackRuleData(AssetPath));
if (YooAssetSettingsData.Setting.RegularBundleName)
bundleName = EditorTools.GetRegularPath(bundleName).Replace('/', '_').Replace('.', '_').ToLower();
else
bundleName = EditorTools.GetRegularPath(bundleName).ToLower();
if (uniqueBundleName)
_shareBundleName = $"{packageName.ToLower()}_share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
else
_shareBundleName = $"share_{bundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
}
}
BundleName = shadersBundleName;
}
else
{
if (IsRawAsset)
if (_referenceBundleNames.Count > 1)
{
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.RawBundleFileVariant}";
_mainBundleName = mainBundleName.ToLower();
IPackRule packRule = PackDirectory.StaticPackRule;
PackRuleResult packRuleResult = packRule.GetPackRuleResult(new PackRuleData(AssetPath));
BundleName = packRuleResult.GetShareBundleName(packageName, uniqueBundleName);
}
else
{
string mainBundleName = $"{_mainBundleName}.{YooAssetSettingsData.Setting.AssetBundleFileVariant}";
_mainBundleName = mainBundleName.ToLower(); ;
}
if (uniqueBundleName)
{
_mainBundleName = $"{packageName.ToLower()}_{_mainBundleName}";
// 注意被引用次数小于1的资源不需要设置资源包名称
BundleName = string.Empty;
}
}
}

View File

@@ -24,6 +24,11 @@ namespace YooAsset.Editor
/// </summary>
public bool UniqueBundleName;
/// <summary>
/// 着色器统一的全名称
/// </summary>
public string ShadersBundleName;
/// <summary>
/// 资源包列表
/// </summary>
@@ -35,7 +40,7 @@ namespace YooAsset.Editor
/// </summary>
public void PackAsset(BuildAssetInfo assetInfo)
{
string bundleName = assetInfo.GetBundleName();
string bundleName = assetInfo.BundleName;
if (string.IsNullOrEmpty(bundleName))
throw new Exception("Should never get here !");

View File

@@ -11,8 +11,7 @@ namespace YooAsset.Editor
/// 执行资源构建上下文
/// </summary>
public static BuildMapContext CreateBuildMap(EBuildMode buildMode, string packageName)
{
BuildMapContext context = new BuildMapContext();
{
Dictionary<string, BuildAssetInfo> buildAssetDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
@@ -22,7 +21,7 @@ namespace YooAsset.Editor
var buildResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(buildMode, packageName);
List<CollectAssetInfo> allCollectAssets = buildResult.CollectAssets;
// 3. 剔除未被引用的依赖资源
// 3. 剔除未被引用的依赖资源
List<CollectAssetInfo> removeDependList = new List<CollectAssetInfo>();
foreach (var collectAssetInfo in allCollectAssets)
{
@@ -42,7 +41,8 @@ namespace YooAsset.Editor
{
if (buildAssetDic.ContainsKey(collectAssetInfo.AssetPath) == false)
{
var buildAssetInfo = new BuildAssetInfo(collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
var buildAssetInfo = new BuildAssetInfo(
collectAssetInfo.CollectorType, collectAssetInfo.BundleName,
collectAssetInfo.Address, collectAssetInfo.AssetPath, collectAssetInfo.IsRawAsset);
buildAssetInfo.AddAssetTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
@@ -54,32 +54,28 @@ namespace YooAsset.Editor
}
}
// 5. 录入相关依赖资源
// 5. 录入所有收集资源的依赖资源
foreach (var collectAssetInfo in allCollectAssets)
{
string collectAssetBundleName = collectAssetInfo.BundleName;
foreach (var dependAssetPath in collectAssetInfo.DependAssets)
{
if (buildAssetDic.ContainsKey(dependAssetPath))
{
buildAssetDic[dependAssetPath].AddBundleTags(collectAssetInfo.AssetTags);
buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetInfo.BundleName);
buildAssetDic[dependAssetPath].AddReferenceBundleName(collectAssetBundleName);
}
else
{
var buildAssetInfo = new BuildAssetInfo(dependAssetPath);
buildAssetInfo.AddBundleTags(collectAssetInfo.AssetTags);
buildAssetInfo.AddReferenceBundleName(collectAssetInfo.BundleName);
buildAssetInfo.AddReferenceBundleName(collectAssetBundleName);
buildAssetDic.Add(dependAssetPath, buildAssetInfo);
}
}
}
// 6. 记录关键信息
context.AssetFileCount = buildAssetDic.Count;
context.EnableAddressable = buildResult.EnableAddressable;
context.UniqueBundleName = buildResult.UniqueBundleName;
// 7. 填充主动收集资源的依赖列表
// 6. 填充所有收集资源的依赖列表
foreach (var collectAssetInfo in allCollectAssets)
{
var dependAssetInfos = new List<BuildAssetInfo>(collectAssetInfo.DependAssets.Count);
@@ -93,10 +89,18 @@ namespace YooAsset.Editor
buildAssetDic[collectAssetInfo.AssetPath].SetAllDependAssetInfos(dependAssetInfos);
}
// 8. 计算完整的资源包名
// 7. 记录关键信息
BuildMapContext context = new BuildMapContext();
context.AssetFileCount = buildAssetDic.Count;
context.EnableAddressable = buildResult.Command.EnableAddressable;
context.UniqueBundleName = buildResult.Command.UniqueBundleName;
context.ShadersBundleName = buildResult.ShadersBundleName;
// 8. 计算共享的资源包名
var command = buildResult.Command;
foreach (KeyValuePair<string, BuildAssetInfo> pair in buildAssetDic)
{
pair.Value.CalculateFullBundleName(buildResult.UniqueBundleName, buildResult.PackageName);
pair.Value.CalculateShareBundleName(command.UniqueBundleName, command.PackageName, buildResult.ShadersBundleName);
}
// 9. 移除不参与构建的资源
@@ -134,7 +138,7 @@ namespace YooAsset.Editor
}
}
BuildRunner.Log($"发现未被依赖的资源并自动移除 : {dependAssetPath}");
BuildLogger.Log($"发现未被依赖的资源并自动移除 : {dependAssetPath}");
return true;
}
}

View File

@@ -7,8 +7,6 @@ namespace YooAsset.Editor
{
public class BuildParametersContext : IContextObject
{
private readonly System.Diagnostics.Stopwatch _buildWatch = new System.Diagnostics.Stopwatch();
private string _pipelineOutputDirectory = string.Empty;
private string _packageOutputDirectory = string.Empty;
@@ -117,22 +115,5 @@ namespace YooAsset.Editor
return buildParams;
}
/// <summary>
/// 获取构建的耗时(单位:秒)
/// </summary>
public float GetBuildingSeconds()
{
float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return seconds;
}
public void BeginWatch()
{
_buildWatch.Start();
}
public void StopWatch()
{
_buildWatch.Stop();
}
}
}

View File

@@ -48,6 +48,11 @@ namespace YooAsset.Editor
/// </summary>
public string[] Tags;
/// <summary>
/// 引用该资源包的ID列表
/// </summary>
public int[] ReferenceIDs;
/// <summary>
/// 获取资源分类标签的字符串
/// </summary>

View File

@@ -0,0 +1,30 @@

namespace YooAsset.Editor
{
public static class BuildLogger
{
/// <summary>
/// 是否启用LOG
/// </summary>
public static bool EnableLog = true;
/// <summary>
/// 日志输出
/// </summary>
public static void Log(string info)
{
if (EnableLog)
{
UnityEngine.Debug.Log(info);
}
}
/// <summary>
/// 日志输出
/// </summary>
public static void Info(string info)
{
UnityEngine.Debug.Log(info);
}
}
}

View File

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

View File

@@ -2,13 +2,19 @@
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Diagnostics;
using UnityEngine;
namespace YooAsset.Editor
{
public class BuildRunner
{
public static bool EnableLog = true;
private static Stopwatch _buildWatch;
/// <summary>
/// 总耗时
/// </summary>
public static int TotalSeconds = 0;
/// <summary>
/// 执行构建流程
@@ -23,17 +29,26 @@ namespace YooAsset.Editor
BuildResult buildResult = new BuildResult();
buildResult.Success = true;
TotalSeconds = 0;
for (int i = 0; i < pipeline.Count; i++)
{
IBuildTask task = pipeline[i];
try
{
_buildWatch = Stopwatch.StartNew();
var taskAttribute = task.GetType().GetCustomAttribute<TaskAttribute>();
Log($"---------------------------------------->{taskAttribute.Desc}<---------------------------------------");
BuildLogger.Log($"---------------------------------------->{taskAttribute.Desc}<---------------------------------------");
task.Run(context);
_buildWatch.Stop();
// 统计耗时
int seconds = GetBuildSeconds();
TotalSeconds += seconds;
BuildLogger.Log($"{taskAttribute.Desc}耗时:{seconds}秒");
}
catch (Exception e)
{
EditorTools.ClearProgressBar();
buildResult.FailedTask = task.GetType().Name;
buildResult.FailedInfo = e.ToString();
buildResult.Success = false;
@@ -42,26 +57,14 @@ namespace YooAsset.Editor
}
// 返回运行结果
BuildLogger.Log($"构建过程总计耗时:{TotalSeconds}秒");
return buildResult;
}
/// <summary>
/// 日志输出
/// </summary>
public static void Log(string info)
private static int GetBuildSeconds()
{
if (EnableLog)
{
UnityEngine.Debug.Log(info);
}
}
/// <summary>
/// 日志输出
/// </summary>
public static void Info(string info)
{
UnityEngine.Debug.Log(info);
float seconds = _buildWatch.ElapsedMilliseconds / 1000f;
return (int)seconds;
}
}
}

View File

@@ -41,36 +41,10 @@ namespace YooAsset.Editor
throw new Exception("构建过程中发生严重错误!请查阅上下文日志!");
}
BuildRunner.Log("Unity引擎打包成功");
BuildLogger.Log("Unity引擎打包成功");
BuildResultContext buildResultContext = new BuildResultContext();
buildResultContext.UnityManifest = buildResults;
context.SetContextObject(buildResultContext);
// 拷贝原生文件
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyRawBundle(buildMapContext, buildParametersContext);
}
}
/// <summary>
/// 拷贝原生文件
/// </summary>
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string dest = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach (var buildAsset in bundleInfo.BuildinAssets)
{
if (buildAsset.IsRawAsset)
EditorTools.CopyFile(buildAsset.AssetPath, dest, true);
}
}
}
}
}
}

View File

@@ -33,44 +33,17 @@ namespace YooAsset.Editor
// 开始构建
IBundleBuildResults buildResults;
var buildParameters = buildParametersContext.GetSBPBuildParameters();
var shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName(buildMapContext.UniqueBundleName, buildParametersContext.Parameters.PackageName);
var taskList = SBPBuildTasks.Create(shadersBunldeName);
var taskList = SBPBuildTasks.Create(buildMapContext.ShadersBundleName);
ReturnCode exitCode = ContentPipeline.BuildAssetBundles(buildParameters, buildContent, out buildResults, taskList);
if (exitCode < 0)
{
throw new Exception($"构建过程中发生错误 : {exitCode}");
}
BuildRunner.Log("Unity引擎打包成功");
BuildLogger.Log("Unity引擎打包成功");
BuildResultContext buildResultContext = new BuildResultContext();
buildResultContext.Results = buildResults;
context.SetContextObject(buildResultContext);
// 拷贝原生文件
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyRawBundle(buildMapContext, buildParametersContext);
}
}
/// <summary>
/// 拷贝原生文件
/// </summary>
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string dest = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach (var buildAsset in bundleInfo.BuildinAssets)
{
if (buildAsset.IsRawAsset)
EditorTools.CopyFile(buildAsset.AssetPath, dest, true);
}
}
}
}
}
}

View File

@@ -94,7 +94,7 @@ namespace YooAsset.Editor
// 刷新目录
AssetDatabase.Refresh();
BuildRunner.Log($"内置文件拷贝完成:{streamingAssetsDirectory}");
BuildLogger.Log($"内置文件拷贝完成:{streamingAssetsDirectory}");
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset.Editor
{
[TaskAttribute("拷贝原生文件")]
public class TaskCopyRawFile : IBuildTask
{
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode == EBuildMode.ForceRebuild || buildMode == EBuildMode.IncrementalBuild)
{
CopyRawBundle(buildMapContext, buildParametersContext);
}
}
/// <summary>
/// 拷贝原生文件
/// </summary>
private void CopyRawBundle(BuildMapContext buildMapContext, BuildParametersContext buildParametersContext)
{
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
if (bundleInfo.IsRawFile)
{
string dest = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
foreach (var buildAsset in bundleInfo.BuildinAssets)
{
if (buildAsset.IsRawAsset)
EditorTools.CopyFile(buildAsset.AssetPath, dest, true);
}
}
}
}
}
}

View File

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

View File

@@ -42,13 +42,32 @@ namespace YooAsset.Editor
patchManifest.AssetList = GetAllPatchAsset(context, patchManifest);
// 更新Unity内置资源包的引用关系
string shadersBunldeName = YooAssetSettingsData.GetUnityShadersBundleFullName(buildMapContext.UniqueBundleName, buildParameters.PackageName);
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
if (buildParameters.BuildMode == EBuildMode.IncrementalBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
UpdateBuiltInBundleReference(patchManifest, buildResultContext.Results, shadersBunldeName);
UpdateBuiltInBundleReference(patchManifest, buildResultContext, buildMapContext.ShadersBundleName);
}
}
// 更新资源包之间的引用关系
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{
if (buildParameters.BuildMode == EBuildMode.IncrementalBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding_SBP.BuildResultContext>();
UpdateScriptPipelineReference(patchManifest, buildResultContext);
}
}
// 更新资源包之间的引用关系
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
{
if (buildParameters.BuildMode != EBuildMode.SimulateBuild)
{
var buildResultContext = context.GetContextObject<TaskBuilding.BuildResultContext>();
UpdateBuiltinPipelineReference(patchManifest, buildResultContext);
}
}
@@ -57,7 +76,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetManifestJsonFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifestTools.SerializeToJson(filePath, patchManifest);
BuildRunner.Log($"创建补丁清单文件:{filePath}");
BuildLogger.Log($"创建补丁清单文件:{filePath}");
}
// 创建补丁清单二进制文件
@@ -67,7 +86,7 @@ namespace YooAsset.Editor
string filePath = $"{packageOutputDirectory}/{fileName}";
PatchManifestTools.SerializeToBinary(filePath, patchManifest);
packageHash = HashUtility.FileMD5(filePath);
BuildRunner.Log($"创建补丁清单文件:{filePath}");
BuildLogger.Log($"创建补丁清单文件:{filePath}");
PatchManifestContext patchManifestContext = new PatchManifestContext();
byte[] bytesData = FileUtility.ReadAllBytes(filePath);
@@ -80,7 +99,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetPackageHashFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(filePath, packageHash);
BuildRunner.Log($"创建补丁清单哈希文件:{filePath}");
BuildLogger.Log($"创建补丁清单哈希文件:{filePath}");
}
// 创建补丁清单版本文件
@@ -88,7 +107,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetPackageVersionFileName(buildParameters.PackageName);
string filePath = $"{packageOutputDirectory}/{fileName}";
FileUtility.CreateFile(filePath, buildParameters.PackageVersion);
BuildRunner.Log($"创建补丁清单版本文件:{filePath}");
BuildLogger.Log($"创建补丁清单版本文件:{filePath}");
}
}
@@ -98,7 +117,6 @@ namespace YooAsset.Editor
private List<PatchBundle> GetAllPatchBundle(BuildContext context)
{
var buildMapContext = context.GetContextObject<BuildMapContext>();
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
List<PatchBundle> result = new List<PatchBundle>(1000);
foreach (var bundleInfo in buildMapContext.BundleInfos)
@@ -129,7 +147,7 @@ namespace YooAsset.Editor
patchAsset.Address = string.Empty;
patchAsset.AssetPath = assetInfo.AssetPath;
patchAsset.AssetTags = assetInfo.AssetTags.ToArray();
patchAsset.BundleID = GetAssetBundleID(assetInfo.GetBundleName(), patchManifest);
patchAsset.BundleID = GetAssetBundleID(assetInfo.BundleName, patchManifest);
patchAsset.DependIDs = GetAssetBundleDependIDs(patchAsset.BundleID, assetInfo, patchManifest);
result.Add(patchAsset);
}
@@ -143,7 +161,7 @@ namespace YooAsset.Editor
{
if (dependAssetInfo.HasBundleName())
{
int bundleID = GetAssetBundleID(dependAssetInfo.GetBundleName(), patchManifest);
int bundleID = GetAssetBundleID(dependAssetInfo.BundleName, patchManifest);
if (mainBundleID != bundleID)
{
if (result.Contains(bundleID) == false)
@@ -166,11 +184,11 @@ namespace YooAsset.Editor
/// <summary>
/// 更新Unity内置资源包的引用关系
/// </summary>
private void UpdateBuiltInBundleReference(PatchManifest patchManifest, IBundleBuildResults buildResults, string shadersBunldeName)
private void UpdateBuiltInBundleReference(PatchManifest patchManifest, TaskBuilding_SBP.BuildResultContext buildResultContext, string shadersBunldeName)
{
// 获取所有依赖着色器资源包的资源包列表
List<string> shaderBundleReferenceList = new List<string>();
foreach (var valuePair in buildResults.BundleInfos)
foreach (var valuePair in buildResultContext.Results.BundleInfos)
{
if (valuePair.Value.Dependencies.Any(t => t == shadersBunldeName))
shaderBundleReferenceList.Add(valuePair.Key);
@@ -212,5 +230,130 @@ namespace YooAsset.Editor
}
return result;
}
#region
private readonly Dictionary<string, int> _cachedBundleID = new Dictionary<string, int>(10000);
private readonly Dictionary<string, string[]> _cachedBundleDepends = new Dictionary<string, string[]>(10000);
private void UpdateScriptPipelineReference(PatchManifest patchManifest, TaskBuilding_SBP.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = patchManifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
int bundleID = GetAssetBundleID(patchBundle.BundleName, patchManifest);
_cachedBundleID.Add(patchBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
if (patchBundle.IsRawFile)
continue;
if (buildResultContext.Results.BundleInfos.ContainsKey(patchBundle.BundleName) == false)
throw new Exception($"Not found bundle in SBP build results : {patchBundle.BundleName}");
var depends = buildResultContext.Results.BundleInfos[patchBundle.BundleName].Dependencies;
_cachedBundleDepends.Add(patchBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
foreach (var patchBundle in patchManifest.BundleList)
{
patchBundle.ReferenceIDs = GetBundleRefrenceIDs(patchManifest, patchBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private void UpdateBuiltinPipelineReference(PatchManifest patchManifest, TaskBuilding.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = patchManifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
int bundleID = GetAssetBundleID(patchBundle.BundleName, patchManifest);
_cachedBundleID.Add(patchBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
var depends = buildResultContext.UnityManifest.GetDirectDependencies(patchBundle.BundleName);
_cachedBundleDepends.Add(patchBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 计算资源包引用列表
progressValue = 0;
foreach (var patchBundle in patchManifest.BundleList)
{
patchBundle.ReferenceIDs = GetBundleRefrenceIDs(patchManifest, patchBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
}
private int[] GetBundleRefrenceIDs(PatchManifest patchManifest, PatchBundle targetBundle)
{
List<string> referenceList = new List<string>();
foreach (var patchBundle in patchManifest.BundleList)
{
string bundleName = patchBundle.BundleName;
if (bundleName == targetBundle.BundleName)
continue;
string[] dependencies = GetCachedBundleDepends(bundleName);
if (dependencies.Contains(targetBundle.BundleName))
{
referenceList.Add(bundleName);
}
}
List<int> result = new List<int>();
foreach (var bundleName in referenceList)
{
int bundleID = GetCachedBundleID(bundleName);
if (result.Contains(bundleID) == false)
result.Add(bundleID);
}
return result.ToArray();
}
private int GetCachedBundleID(string bundleName)
{
if (_cachedBundleID.TryGetValue(bundleName, out int value) == false)
{
throw new Exception($"Not found cached bundle ID : {bundleName}");
}
return value;
}
private string[] GetCachedBundleDepends(string bundleName)
{
if (_cachedBundleDepends.TryGetValue(bundleName, out string[] value) == false)
{
throw new Exception($"Not found cached bundle depends : {bundleName}");
}
return value;
}
#endregion
}
}

View File

@@ -25,7 +25,7 @@ namespace YooAsset.Editor
var buildParameters = buildParametersContext.Parameters;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
string packageOutputDirectory = buildParametersContext.GetPackageOutputDirectory();
BuildRunner.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}");
BuildLogger.Log($"开始拷贝补丁文件到补丁包目录:{packageOutputDirectory}");
if (buildParameters.BuildPipeline == EBuildPipeline.ScriptableBuildPipeline)
{

View File

@@ -13,16 +13,12 @@ namespace YooAsset.Editor
var buildParameters = context.GetContextObject<BuildParametersContext>();
var buildMapContext = context.GetContextObject<BuildMapContext>();
var patchManifestContext = context.GetContextObject<PatchManifestContext>();
buildParameters.StopWatch();
var buildMode = buildParameters.Parameters.BuildMode;
if (buildMode != EBuildMode.SimulateBuild)
{
CreateReportFile(buildParameters, buildMapContext, patchManifestContext);
}
float buildSeconds = buildParameters.GetBuildingSeconds();
BuildRunner.Info($"Build time consuming {buildSeconds} seconds.");
}
private void CreateReportFile(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext, PatchManifestContext patchManifestContext)
@@ -42,7 +38,7 @@ namespace YooAsset.Editor
#endif
buildReport.Summary.UnityVersion = UnityEngine.Application.unityVersion;
buildReport.Summary.BuildDate = DateTime.Now.ToString();
buildReport.Summary.BuildSeconds = (int)buildParametersContext.GetBuildingSeconds();
buildReport.Summary.BuildSeconds = BuildRunner.TotalSeconds;
buildReport.Summary.BuildTarget = buildParameters.BuildTarget;
buildReport.Summary.BuildPipeline = buildParameters.BuildPipeline;
buildReport.Summary.BuildMode = buildParameters.BuildMode;
@@ -98,6 +94,7 @@ namespace YooAsset.Editor
reportBundleInfo.FileCRC = patchBundle.FileCRC;
reportBundleInfo.FileSize = patchBundle.FileSize;
reportBundleInfo.Tags = patchBundle.Tags;
reportBundleInfo.ReferenceIDs = patchBundle.ReferenceIDs;
reportBundleInfo.IsRawFile = patchBundle.IsRawFile;
reportBundleInfo.LoadMethod = (EBundleLoadMethod)patchBundle.LoadMethod;
buildReport.BundleInfos.Add(reportBundleInfo);
@@ -107,7 +104,7 @@ namespace YooAsset.Editor
string fileName = YooAssetSettingsData.GetReportFileName(buildParameters.PackageName, buildParameters.PackageVersion);
string filePath = $"{packageOutputDirectory}/{fileName}";
BuildReport.Serialize(filePath, buildReport);
BuildRunner.Log($"资源构建报告文件创建完成:{filePath}");
BuildLogger.Log($"资源构建报告文件创建完成:{filePath}");
}
/// <summary>

View File

@@ -27,17 +27,16 @@ namespace YooAsset.Editor
private void EncryptingBundleFiles(BuildParametersContext buildParametersContext, BuildMapContext buildMapContext)
{
var encryptionServices = buildParametersContext.Parameters.EncryptionServices;
// 如果没有设置加密类
if (encryptionServices == null)
return;
if (encryptionServices.GetType() == typeof(EncryptionNone))
return;
int progressValue = 0;
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
bundleInfo.LoadMethod = EBundleLoadMethod.Normal;
EncryptFileInfo fileInfo = new EncryptFileInfo();
fileInfo.BundleName = bundleInfo.BundleName;
fileInfo.FilePath = $"{pipelineOutputDirectory}/{bundleInfo.BundleName}";
@@ -56,7 +55,7 @@ namespace YooAsset.Editor
FileUtility.CreateFile(filePath, encryptResult.EncryptedData);
bundleInfo.EncryptedFilePath = filePath;
bundleInfo.LoadMethod = encryptResult.LoadMethod;
BuildRunner.Log($"Bundle文件加密完成{filePath}");
BuildLogger.Log($"Bundle文件加密完成{filePath}");
}
// 进度条

View File

@@ -15,7 +15,7 @@ namespace YooAsset.Editor
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
var buildMapContext = BuildMapCreater.CreateBuildMap(buildParametersContext.Parameters.BuildMode, buildParametersContext.Parameters.PackageName);
context.SetContextObject(buildMapContext);
BuildRunner.Log("构建内容准备完毕!");
BuildLogger.Log("构建内容准备完毕!");
// 检测构建结果
CheckBuildMapContent(buildMapContext);

View File

@@ -12,15 +12,8 @@ namespace YooAsset.Editor
void IBuildTask.Run(BuildContext context)
{
var buildParametersContext = context.GetContextObject<BuildParametersContext>();
buildParametersContext.BeginWatch();
var buildParameters = buildParametersContext.Parameters;
#if !UNITY_2021_1_OR_NEWER
if (buildParameters.BuildPipeline == EBuildPipeline.BuiltinBuildPipeline)
throw new Exception($"Unity2021 or newer not support {nameof(EBuildPipeline.BuiltinBuildPipeline)}, Please use {nameof(EBuildPipeline.ScriptableBuildPipeline)}");
#endif
// 检测构建参数合法性
if (buildParameters.BuildTarget == BuildTarget.NoTarget)
throw new Exception("请选择目标平台");
@@ -62,7 +55,7 @@ namespace YooAsset.Editor
string platformDirectory = $"{buildParameters.OutputRoot}/{buildParameters.PackageName}/{buildParameters.BuildTarget}";
if (EditorTools.DeleteDirectory(platformDirectory))
{
BuildRunner.Log($"删除平台总目录:{platformDirectory}");
BuildLogger.Log($"删除平台总目录:{platformDirectory}");
}
}
@@ -70,7 +63,7 @@ namespace YooAsset.Editor
string pipelineOutputDirectory = buildParametersContext.GetPipelineOutputDirectory();
if (EditorTools.CreateDirectory(pipelineOutputDirectory))
{
BuildRunner.Log($"创建输出目录:{pipelineOutputDirectory}");
BuildLogger.Log($"创建输出目录:{pipelineOutputDirectory}");
}
}
}

View File

@@ -48,7 +48,8 @@ namespace YooAsset.Editor
// 4.更新补丁包输出的文件路径
foreach (var bundleInfo in buildMapContext.BundleInfos)
{
string patchFileName = PatchManifestTools.CreateBundleFileName(outputNameStyle, bundleInfo.BundleName, bundleInfo.PatchInfo.PatchFileHash, bundleInfo.IsRawFile);
string patchFileExtension = PatchManifestTools.GetRemoteBundleFileExtension(bundleInfo.BundleName);
string patchFileName = PatchManifestTools.GetRemoteBundleFileName(outputNameStyle, bundleInfo.BundleName, patchFileExtension, bundleInfo.PatchInfo.PatchFileHash);
bundleInfo.PatchInfo.PatchOutputFilePath = $"{packageOutputDirectory}/{patchFileName}";
}
}

View File

@@ -101,7 +101,7 @@ namespace YooAsset.Editor
}
*/
BuildRunner.Log("构建结果验证成功!");
BuildLogger.Log("构建结果验证成功!");
}
/// <summary>

View File

@@ -62,7 +62,7 @@ namespace YooAsset.Editor
throw new System.Exception("存在差异资源包!请查看警告信息!");
}
BuildRunner.Log("构建结果验证成功!");
BuildLogger.Log("构建结果验证成功!");
}
}
}

View File

@@ -0,0 +1,11 @@

namespace YooAsset.Editor
{
public class EncryptionNone : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
throw new System.NotImplementedException();
}
}
}

View File

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

View File

@@ -45,6 +45,11 @@ namespace YooAsset.Editor
/// </summary>
public string AssetTags = string.Empty;
/// <summary>
/// 用户自定义数据
/// </summary>
public string UserData = string.Empty;
/// <summary>
/// 收集器是否有效
@@ -142,11 +147,14 @@ namespace YooAsset.Editor
}
Dictionary<string, CollectAssetInfo> result = new Dictionary<string, CollectAssetInfo>(1000);
bool isRawAsset = PackRuleName == nameof(PackRawFile);
// 检测是否为原生资源打包规则
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
bool isRawFilePackRule = packRuleInstance.IsRawFilePackRule();
// 检测原生资源包的收集器类型
if (isRawAsset && CollectorType != ECollectorType.MainAssetCollector)
throw new Exception($"The raw file must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}");
if (isRawFilePackRule && CollectorType != ECollectorType.MainAssetCollector)
throw new Exception($"The raw file pack rule must be set to {nameof(ECollectorType)}.{ECollectorType.MainAssetCollector} : {CollectPath}");
if (string.IsNullOrEmpty(CollectPath))
throw new Exception($"The collect path is null or empty in group : {group.GroupName}");
@@ -158,11 +166,11 @@ namespace YooAsset.Editor
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
foreach (string assetPath in findAssets)
{
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
{
if (result.ContainsKey(assetPath) == false)
{
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawAsset);
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawFilePackRule);
result.Add(assetPath, collectAssetInfo);
}
else
@@ -175,9 +183,9 @@ namespace YooAsset.Editor
else
{
string assetPath = CollectPath;
if (IsValidateAsset(assetPath) && IsCollectAsset(assetPath))
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
{
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawAsset);
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawFilePackRule);
result.Add(assetPath, collectAssetInfo);
}
else
@@ -207,22 +215,22 @@ namespace YooAsset.Editor
return result.Values.ToList();
}
private CollectAssetInfo CreateCollectAssetInfo(CollectCommand command, AssetBundleCollectorGroup group, string assetPath, bool isRawAsset)
private CollectAssetInfo CreateCollectAssetInfo(CollectCommand command, AssetBundleCollectorGroup group, string assetPath, bool isRawFilePackRule)
{
string address = GetAddress(group, assetPath);
string bundleName = GetBundleName(group, assetPath);
string bundleName = GetBundleName(command, group, assetPath);
List<string> assetTags = GetAssetTags(group);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, assetTags, isRawAsset);
CollectAssetInfo collectAssetInfo = new CollectAssetInfo(CollectorType, bundleName, address, assetPath, isRawFilePackRule, assetTags);
// 注意:模拟构建模式下不需要收集依赖资源
if (command.BuildMode == EBuildMode.SimulateBuild)
collectAssetInfo.DependAssets = new List<string>();
else
collectAssetInfo.DependAssets = GetAllDependencies(assetPath);
collectAssetInfo.DependAssets = GetAllDependencies(assetPath, isRawFilePackRule);
return collectAssetInfo;
}
private bool IsValidateAsset(string assetPath)
private bool IsValidateAsset(string assetPath, bool isRawFilePackRule)
{
if (assetPath.StartsWith("Assets/") == false && assetPath.StartsWith("Packages/") == false)
{
@@ -239,10 +247,31 @@ namespace YooAsset.Editor
if (type == typeof(LightingDataAsset))
return false;
// 忽略Unity无法识别的无效文件
// 注意:只对非原生文件收集器处理
if(PackRuleName != nameof(PackRawFile))
// 检测原生文件是否合规
if (isRawFilePackRule)
{
string extension = StringUtility.RemoveFirstChar(System.IO.Path.GetExtension(assetPath));
if (extension == EAssetFileExtension.unity.ToString() || extension == EAssetFileExtension.prefab.ToString() ||
extension == EAssetFileExtension.mat.ToString() || extension == EAssetFileExtension.controller.ToString() ||
extension == EAssetFileExtension.fbx.ToString() || extension == EAssetFileExtension.anim.ToString() ||
extension == EAssetFileExtension.shader.ToString())
{
UnityEngine.Debug.LogWarning($"Raw file pack rule can not support file estension : {extension}");
return false;
}
// 注意:原生文件只支持无依赖关系的资源
string[] depends = AssetDatabase.GetDependencies(assetPath, true);
if (depends.Length != 1)
{
UnityEngine.Debug.LogWarning($"Raw file pack rule can not support estension : {extension}");
return false;
}
}
else
{
// 忽略Unity无法识别的无效文件
// 注意:只对非原生文件收集器处理
if (type == typeof(UnityEditor.DefaultAsset))
{
UnityEngine.Debug.LogWarning($"Cannot pack default asset : {assetPath}");
@@ -258,7 +287,7 @@ namespace YooAsset.Editor
}
private bool IsIgnoreFile(string fileExtension)
{
foreach (var extension in YooAssetSettings.IgnoreFileExtensions)
foreach (var extension in DefaultFilterRule.IgnoreFileExtensions)
{
if (extension == fileExtension)
return true;
@@ -281,22 +310,25 @@ namespace YooAsset.Editor
return string.Empty;
IAddressRule addressRuleInstance = AssetBundleCollectorSettingData.GetAddressRuleInstance(AddressRuleName);
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName));
string adressValue = addressRuleInstance.GetAssetAddress(new AddressRuleData(assetPath, CollectPath, group.GroupName, UserData));
return adressValue;
}
private string GetBundleName(AssetBundleCollectorGroup group, string assetPath)
private string GetBundleName(CollectCommand command, AssetBundleCollectorGroup group, string assetPath)
{
System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(UnityEngine.Shader) || assetType == typeof(UnityEngine.ShaderVariantCollection))
return EditorTools.GetRegularPath(YooAssetSettings.UnityShadersBundleName).ToLower();
// 根据规则设置获取资源包名称
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
string bundleName = packRuleInstance.GetBundleName(new PackRuleData(assetPath, CollectPath, group.GroupName));
if(YooAssetSettingsData.Setting.RegularBundleName)
return EditorTools.GetRegularPath(bundleName).Replace('/', '_').Replace('.', '_').ToLower();
{
// 获取着色器打包规则结果
PackRuleResult packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
return packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
}
else
return EditorTools.GetRegularPath(bundleName).ToLower();
{
// 获取其它资源打包规则结果
IPackRule packRuleInstance = AssetBundleCollectorSettingData.GetPackRuleInstance(PackRuleName);
PackRuleResult packRuleResult = packRuleInstance.GetPackRuleResult(new PackRuleData(assetPath, CollectPath, group.GroupName, UserData));
return packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
}
}
private List<string> GetAssetTags(AssetBundleCollectorGroup group)
{
@@ -305,13 +337,13 @@ namespace YooAsset.Editor
tags.AddRange(temper);
return tags;
}
private List<string> GetAllDependencies(string mainAssetPath)
private List<string> GetAllDependencies(string mainAssetPath, bool isRawFilePackRule)
{
List<string> result = new List<string>();
string[] depends = AssetDatabase.GetDependencies(mainAssetPath, true);
foreach (string assetPath in depends)
{
if (IsValidateAsset(assetPath))
if (IsValidateAsset(assetPath, isRawFilePackRule))
{
// 注意:排除主资源对象
if (assetPath != mainAssetPath)

View File

@@ -10,7 +10,7 @@ namespace YooAsset.Editor
{
public class AssetBundleCollectorConfig
{
public const string ConfigVersion = "2.2";
public const string ConfigVersion = "2.3";
public const string XmlVersion = "Version";
public const string XmlCommon = "Common";
@@ -34,6 +34,7 @@ namespace YooAsset.Editor
public const string XmlAddressRule = "AddressRule";
public const string XmlPackRule = "PackRule";
public const string XmlFilterRule = "FilterRule";
public const string XmlUserData = "UserData";
public const string XmlAssetTags = "AssetTags";
/// <summary>
@@ -137,6 +138,8 @@ namespace YooAsset.Editor
throw new Exception($"Not found attribute {XmlPackRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlFilterRule) == false)
throw new Exception($"Not found attribute {XmlFilterRule} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlUserData) == false)
throw new Exception($"Not found attribute {XmlUserData} in {XmlCollector}");
if (collectorElement.HasAttribute(XmlAssetTags) == false)
throw new Exception($"Not found attribute {XmlAssetTags} in {XmlCollector}");
@@ -147,6 +150,7 @@ namespace YooAsset.Editor
collector.AddressRuleName = collectorElement.GetAttribute(XmlAddressRule);
collector.PackRuleName = collectorElement.GetAttribute(XmlPackRule);
collector.FilterRuleName = collectorElement.GetAttribute(XmlFilterRule);
collector.UserData = collectorElement.GetAttribute(XmlUserData);
collector.AssetTags = collectorElement.GetAttribute(XmlAssetTags);
group.Collectors.Add(collector);
}
@@ -219,6 +223,7 @@ namespace YooAsset.Editor
collectorElement.SetAttribute(XmlAddressRule, collector.AddressRuleName);
collectorElement.SetAttribute(XmlPackRule, collector.PackRuleName);
collectorElement.SetAttribute(XmlFilterRule, collector.FilterRuleName);
collectorElement.SetAttribute(XmlUserData, collector.UserData);
collectorElement.SetAttribute(XmlAssetTags, collector.AssetTags);
groupElement.AppendChild(collectorElement);
}
@@ -320,6 +325,28 @@ namespace YooAsset.Editor
return UpdateXmlConfig(xmlDoc);
}
// 2.2 -> 2.3
if (configVersion == "2.2")
{
// 获取所有分组元素
var groupNodeList = root.GetElementsByTagName(XmlGroup);
foreach (var groupNode in groupNodeList)
{
XmlElement groupElement = groupNode as XmlElement;
var collectorNodeList = groupElement.GetElementsByTagName(XmlCollector);
foreach (var collectorNode in collectorNodeList)
{
XmlElement collectorElement = collectorNode as XmlElement;
if (collectorElement.HasAttribute(XmlUserData) == false)
collectorElement.SetAttribute(XmlUserData, string.Empty);
}
}
// 更新版本
root.SetAttribute(XmlVersion, "2.3");
return UpdateXmlConfig(xmlDoc);
}
return false;
}
}

View File

@@ -100,8 +100,8 @@ namespace YooAsset.Editor
{
if (package.PackageName == packageName)
{
CollectCommand command = new CollectCommand(buildMode, EnableAddressable);
CollectResult collectResult = new CollectResult(package.PackageName, EnableAddressable, UniqueBundleName);
CollectCommand command = new CollectCommand(buildMode, package.PackageName, EnableAddressable, UniqueBundleName);
CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
return collectResult;
}
@@ -118,8 +118,8 @@ namespace YooAsset.Editor
List<CollectResult> collectResultList = new List<CollectResult>(1000);
foreach (var package in Packages)
{
CollectCommand command = new CollectCommand(buildMode, EnableAddressable);
CollectResult collectResult = new CollectResult(package.PackageName, EnableAddressable, UniqueBundleName);
CollectCommand command = new CollectCommand(buildMode, package.PackageName, EnableAddressable, UniqueBundleName);
CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
collectResultList.Add(collectResult);
}

View File

@@ -108,7 +108,7 @@ namespace YooAsset.Editor
List<Type> types = new List<Type>(100)
{
typeof(AddressByFileName),
typeof(AddressByCollectorAndFileName),
typeof(AddressByFolderAndFileName),
typeof(AddressByGroupAndFileName)
};

View File

@@ -594,14 +594,14 @@ namespace YooAsset.Editor
var popupField = new PopupField<RuleDisplayName>(_addressRuleList, 0);
popupField.name = "PopupField1";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 200;
popupField.style.width = 220;
elementBottom.Add(popupField);
}
{
var popupField = new PopupField<RuleDisplayName>(_packRuleList, 0);
popupField.name = "PopupField2";
popupField.style.unityTextAlign = TextAnchor.MiddleLeft;
popupField.style.width = 230;
popupField.style.width = 220;
elementBottom.Add(popupField);
}
{
@@ -611,6 +611,15 @@ namespace YooAsset.Editor
popupField.style.width = 150;
elementBottom.Add(popupField);
}
{
var textField = new TextField();
textField.name = "TextField0";
textField.label = "UserData";
textField.style.width = 200;
elementBottom.Add(textField);
var label = textField.Q<Label>();
label.style.minWidth = 63;
}
{
var textField = new TextField();
textField.name = "TextField1";
@@ -750,6 +759,15 @@ namespace YooAsset.Editor
}
});
// UserData
var textFiled0 = element.Q<TextField>("TextField0");
textFiled0.SetValueWithoutNotify(collector.UserData);
textFiled0.RegisterValueChangedCallback(evt =>
{
collector.UserData = evt.newValue;
AssetBundleCollectorSettingData.ModifyCollector(selectGroup, collector);
});
// Tags
var textFiled1 = element.Q<TextField>("TextField1");
textFiled1.SetValueWithoutNotify(collector.AssetTags);
@@ -776,7 +794,7 @@ namespace YooAsset.Editor
try
{
CollectCommand command = new CollectCommand(EBuildMode.DryRunBuild, _enableAddressableToogle.value);
CollectCommand command = new CollectCommand(EBuildMode.SimulateBuild, _packageNameTxt.value, _enableAddressableToogle.value, _uniqueBundleNameToogle.value);
collectAssetInfos = collector.GetAllCollectAssets(command, group);
}
catch (System.Exception e)
@@ -794,12 +812,7 @@ namespace YooAsset.Editor
string showInfo = collectAssetInfo.AssetPath;
if (_enableAddressableToogle.value)
{
IAddressRule instance = AssetBundleCollectorSettingData.GetAddressRuleInstance(collector.AddressRuleName);
AddressRuleData ruleData = new AddressRuleData(collectAssetInfo.AssetPath, collector.CollectPath, group.GroupName);
string addressValue = instance.GetAssetAddress(ruleData);
showInfo = $"[{addressValue}] {showInfo}";
}
showInfo = $"[{collectAssetInfo.Address}] {collectAssetInfo.AssetPath}";
var label = new Label();
label.text = showInfo;

View File

@@ -14,7 +14,7 @@ namespace YooAsset.Editor
/// 资源包名称
/// </summary>
public string BundleName { private set; get; }
/// <summary>
/// 可寻址地址
/// </summary>
@@ -25,30 +25,30 @@ namespace YooAsset.Editor
/// </summary>
public string AssetPath { private set; get; }
/// <summary>
/// 资源分类标签
/// </summary>
public List<string> AssetTags { private set; get; }
/// <summary>
/// 是否为原生资源
/// </summary>
public bool IsRawAsset { private set; get; }
/// <summary>
/// 资源分类标签
/// </summary>
public List<string> AssetTags { private set; get; }
/// <summary>
/// 依赖的资源列表
/// </summary>
public List<string> DependAssets = new List<string>();
public CollectAssetInfo(ECollectorType collectorType, string bundleName, string address, string assetPath, List<string> assetTags, bool isRawAsset)
public CollectAssetInfo(ECollectorType collectorType, string bundleName, string address, string assetPath, bool isRawAsset, List<string> assetTags)
{
CollectorType = collectorType;
BundleName = bundleName;
Address = address;
AssetPath = assetPath;
AssetTags = assetTags;
IsRawAsset = isRawAsset;
AssetTags = assetTags;
}
}
}

View File

@@ -8,15 +8,27 @@ namespace YooAsset.Editor
/// </summary>
public EBuildMode BuildMode { private set; get; }
/// <summary>
/// 包裹名称
/// </summary>
public string PackageName { private set; get; }
/// <summary>
/// 是否启用可寻址资源定位
/// </summary>
public bool EnableAddressable { private set; get; }
public CollectCommand(EBuildMode buildMode, bool enableAddressable)
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName { private set; get; }
public CollectCommand(EBuildMode buildMode, string packageName, bool enableAddressable, bool uniqueBundleName)
{
BuildMode = buildMode;
PackageName = packageName;
EnableAddressable = enableAddressable;
UniqueBundleName = uniqueBundleName;
}
}
}

View File

@@ -6,19 +6,14 @@ namespace YooAsset.Editor
public class CollectResult
{
/// <summary>
/// 包裹名称
/// 收集命令
/// </summary>
public string PackageName { private set; get; }
public CollectCommand Command { private set; get; }
/// <summary>
/// 是否启用可寻址资源定位
/// 着色器统一全名称
/// </summary>
public bool EnableAddressable { private set; get; }
/// <summary>
/// 资源包名唯一化
/// </summary>
public bool UniqueBundleName { private set; get; }
public string ShadersBundleName { private set; get; }
/// <summary>
/// 收集的资源信息列表
@@ -26,11 +21,13 @@ namespace YooAsset.Editor
public List<CollectAssetInfo> CollectAssets { private set; get; }
public CollectResult(string packageName, bool enableAddressable, bool uniqueBundleName)
public CollectResult(CollectCommand command)
{
PackageName = packageName;
EnableAddressable = enableAddressable;
UniqueBundleName = uniqueBundleName;
Command = command;
// 着色器统一全名称
var packRuleResult = DefaultPackRule.CreateShadersPackRuleResult();
ShadersBundleName = packRuleResult.GetMainBundleName(command.PackageName, command.UniqueBundleName);
}
public void SetCollectAssets(List<CollectAssetInfo> collectAssets)

View File

@@ -2,7 +2,7 @@
namespace YooAsset.Editor
{
[DisplayName("以文件名称为定位地址")]
[DisplayName("定位地址: 文件名")]
public class AddressByFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
@@ -11,7 +11,7 @@ namespace YooAsset.Editor
}
}
[DisplayName("分组名+文件名称为定位地址")]
[DisplayName("定位地址: 分组名+文件名")]
public class AddressByGroupAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
@@ -21,8 +21,8 @@ namespace YooAsset.Editor
}
}
[DisplayName("以收集器名称+文件名称为定位地址")]
public class AddressByCollectorAndFileName : IAddressRule
[DisplayName("定位地址: 文件夹名+文件名")]
public class AddressByFolderAndFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{

View File

@@ -4,6 +4,14 @@ using System.IO;
namespace YooAsset.Editor
{
public class DefaultFilterRule
{
/// <summary>
/// 忽略的文件类型
/// </summary>
public static readonly string[] IgnoreFileExtensions = { "", ".so", ".dll", ".cs", ".js", ".boo", ".meta", ".cginc", ".hlsl" };
}
[DisplayName("收集所有资源")]
public class CollectAll : IFilterRule
{

View File

@@ -4,18 +4,50 @@ using UnityEditor;
namespace YooAsset.Editor
{
public class DefaultPackRule
{
/// <summary>
/// AssetBundle文件的后缀名
/// </summary>
public const string AssetBundleFileExtension = "bundle";
/// <summary>
/// 原生文件的后缀名
/// </summary>
public const string RawFileExtension = "rawfile";
/// <summary>
/// Unity着色器资源包名称
/// </summary>
public const string ShadersBundleName = "unityshaders";
public static PackRuleResult CreateShadersPackRuleResult()
{
PackRuleResult result = new PackRuleResult(ShadersBundleName, AssetBundleFileExtension);
return result;
}
}
/// <summary>
/// 以文件路径作为资源包名
/// 注意:每个文件独自打资源包
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image_backgroud.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view_main.bundle"
/// </summary>
[DisplayName("以文件路径作为资源包名")]
[DisplayName("资源包名: 文件路径")]
public class PackSeparately : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
return StringUtility.RemoveExtension(data.AssetPath);
string bundleName = StringUtility.RemoveExtension(data.AssetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
@@ -25,14 +57,21 @@ namespace YooAsset.Editor
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop_image.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop_view.bundle"
/// </summary>
[DisplayName("父类文件夹路径作为资源包名")]
[DisplayName("资源包名: 父类文件夹路径")]
public class PackDirectory : IPackRule
{
public static PackDirectory StaticPackRule = new PackDirectory();
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
return Path.GetDirectoryName(data.AssetPath);
string bundleName = Path.GetDirectoryName(data.AssetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
@@ -43,10 +82,10 @@ namespace YooAsset.Editor
/// 例如:"Assets/UIPanel/Shop/Image/backgroud.png" --> "assets_uipanel_shop.bundle"
/// 例如:"Assets/UIPanel/Shop/View/main.prefab" --> "assets_uipanel_shop.bundle"
/// </summary>
[DisplayName("收集器路径下顶级文件夹为资源包名")]
[DisplayName("资源包名: 收集器下顶级文件夹路径")]
public class PackTopDirectory : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string assetPath = data.AssetPath.Replace(data.CollectPath, string.Empty);
assetPath = assetPath.TrimStart('/');
@@ -56,33 +95,48 @@ namespace YooAsset.Editor
if (Path.HasExtension(splits[0]))
throw new Exception($"Not found root directory : {assetPath}");
string bundleName = $"{data.CollectPath}/{splits[0]}";
return bundleName;
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
else
{
throw new Exception($"Not found root directory : {assetPath}");
}
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 以收集器路径作为资源包名
/// 注意:收集的所有文件打进一个资源包
/// </summary>
[DisplayName("以收集器路径作为资源包名")]
[DisplayName("资源包名: 收集器路径")]
public class PackCollector : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string bundleName;
string collectPath = data.CollectPath;
if (AssetDatabase.IsValidFolder(collectPath))
{
return collectPath;
bundleName = collectPath;
}
else
{
return StringUtility.RemoveExtension(collectPath);
bundleName = StringUtility.RemoveExtension(collectPath);
}
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
@@ -90,51 +144,55 @@ namespace YooAsset.Editor
/// 以分组名称作为资源包名
/// 注意:收集的所有文件打进一个资源包
/// </summary>
[DisplayName("以分组名称作为资源包名")]
[DisplayName("资源包名: 分组名称")]
public class PackGroup : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
return data.GroupName;
string bundleName = data.GroupName;
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
/// <summary>
/// 打包原生文件
/// 注意:原生文件打包支持:图片,音频,视频,文本
/// </summary>
[DisplayName("打包原生文件")]
public class PackRawFile : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string extension = StringUtility.RemoveFirstChar(Path.GetExtension(data.AssetPath));
if (extension == EAssetFileExtension.unity.ToString() || extension == EAssetFileExtension.prefab.ToString() ||
extension == EAssetFileExtension.mat.ToString() || extension == EAssetFileExtension.controller.ToString() ||
extension == EAssetFileExtension.fbx.ToString() || extension == EAssetFileExtension.anim.ToString() ||
extension == EAssetFileExtension.shader.ToString())
{
throw new Exception($"{nameof(PackRawFile)} is not support file estension : {extension}");
}
string bundleName = data.AssetPath;
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.RawFileExtension);
return result;
}
// 注意:原生文件只支持无依赖关系的资源
string[] depends = AssetDatabase.GetDependencies(data.AssetPath, true);
if (depends.Length != 1)
throw new Exception($"{nameof(PackRawFile)} is not support estension : {extension}");
return data.AssetPath;
bool IPackRule.IsRawFilePackRule()
{
return true;
}
}
/// <summary>
/// 打包着色器变种集合
/// </summary>
[DisplayName("打包着色器变种集合")]
[DisplayName("打包着色器变种集合文件")]
public class PackShaderVariants : IPackRule
{
public string GetBundleName(PackRuleData data)
public PackRuleResult GetPackRuleResult(PackRuleData data)
{
return YooAssetSettings.UnityShadersBundleName;
return DefaultPackRule.CreateShadersPackRuleResult();
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
}

View File

@@ -6,12 +6,14 @@ namespace YooAsset.Editor
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
public AddressRuleData(string assetPath, string collectPath, string groupName)
public AddressRuleData(string assetPath, string collectPath, string groupName, string userData)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
UserData = userData;
}
}

View File

@@ -3,21 +3,64 @@ namespace YooAsset.Editor
{
public struct PackRuleData
{
public string AssetPath;
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
public PackRuleData(string assetPath)
{
AssetPath = assetPath;
CollectPath = string.Empty;
GroupName = string.Empty;
UserData = string.Empty;
}
public PackRuleData(string assetPath, string collectPath, string groupName)
public PackRuleData(string assetPath, string collectPath, string groupName, string userData)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
UserData = userData;
}
}
public struct PackRuleResult
{
private readonly string _bundleName;
private readonly string _bundleExtension;
public PackRuleResult(string bundleName, string bundleExtension)
{
_bundleName = bundleName;
_bundleExtension = bundleExtension;
}
/// <summary>
/// 获取主资源包全名称
/// </summary>
public string GetMainBundleName(string packageName, bool uniqueBundleName)
{
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_{bundleName}.{_bundleExtension}";
else
fullName = $"{bundleName}.{_bundleExtension}";
return fullName.ToLower();
}
/// <summary>
/// 获取共享资源包全名称
/// </summary>
public string GetShareBundleName(string packageName, bool uniqueBundleName)
{
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_share_{bundleName}.{_bundleExtension}";
else
fullName = $"share_{bundleName}.{_bundleExtension}";
return fullName.ToLower();
}
}
@@ -27,8 +70,13 @@ namespace YooAsset.Editor
public interface IPackRule
{
/// <summary>
/// 获取资源打包所属的资源包名称
/// 获取打包规则结果
/// </summary>
string GetBundleName(PackRuleData data);
PackRuleResult GetPackRuleResult(PackRuleData data);
/// <summary>
/// 是否为原生文件打包规则
/// </summary>
bool IsRawFilePackRule();
}
}

View File

@@ -1,10 +1,10 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Asset Path" display-tooltip-when-elided="true" name="TopBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Main Bundle" display-tooltip-when-elided="true" name="TopBar2" style="width: 145px; -unity-text-align: middle-left; flex-grow: 1;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1; flex-basis: 60px;" />
</ui:VisualElement>
<ui:VisualElement name="BottomGroup" style="height: 200px; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 1px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="BottomBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">

View File

@@ -1,4 +1,4 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<ui:VisualElement name="Viewer" style="flex-grow: 1; display: flex;">
<ui:VisualElement name="TopGroup" style="flex-grow: 1; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 2px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="TopBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
@@ -8,7 +8,7 @@
<uie:ToolbarButton text="LoadMethod" display-tooltip-when-elided="true" name="TopBar4" style="width: 150px; -unity-text-align: middle-left; flex-grow: 0;" />
<uie:ToolbarButton text="Tags" display-tooltip-when-elided="true" name="TopBar5" style="width: 80px; -unity-text-align: middle-left; flex-grow: 1;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />
<ui:ListView focusable="true" name="TopListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1; flex-basis: 60px;" />
</ui:VisualElement>
<ui:VisualElement name="BottomGroup" style="height: 200px; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 1px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="BottomBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">

View File

@@ -27,7 +27,6 @@ namespace YooAsset.Editor
private TemplateContainer _root;
private ListView _listView;
private BuildReport _buildReport;
private readonly List<ItemWrapper> _items = new List<ItemWrapper>();
@@ -55,14 +54,12 @@ namespace YooAsset.Editor
/// </summary>
public void FillViewData(BuildReport buildReport)
{
_buildReport = buildReport;
_items.Clear();
_items.Add(new ItemWrapper("YooAsset版本", buildReport.Summary.YooVersion));
_items.Add(new ItemWrapper("引擎版本", buildReport.Summary.UnityVersion));
_items.Add(new ItemWrapper("构建时间", buildReport.Summary.BuildDate));
_items.Add(new ItemWrapper("构建耗时", $"{buildReport.Summary.BuildSeconds}秒"));
_items.Add(new ItemWrapper("构建耗时", ConvertTime(buildReport.Summary.BuildSeconds)));
_items.Add(new ItemWrapper("构建平台", $"{buildReport.Summary.BuildTarget}"));
_items.Add(new ItemWrapper("构建管线", $"{buildReport.Summary.BuildPipeline}"));
_items.Add(new ItemWrapper("构建模式", $"{buildReport.Summary.BuildMode}"));
@@ -154,16 +151,23 @@ namespace YooAsset.Editor
label2.text = itemWrapper.Value;
}
private string ConvertTime(int time)
{
if (time <= 60)
{
return $"{time}秒钟";
}
else
{
int minute = time / 60;
return $"{minute}分钟";
}
}
private string ConvertSize(long size)
{
if (size == 0)
return "0";
if (size < 1024)
return $"{size} Bytes";
else if (size < 1024 * 1024)
return $"{(int)(size / 1024)} KB";
else
return $"{(int)(size / (1024 * 1024))} MB";
return EditorUtility.FormatBytes(size);
}
}
}

View File

@@ -13,5 +13,10 @@ namespace YooAsset.Editor
/// 收集的包裹名称
/// </summary>
public string CollectPackage = string.Empty;
/// <summary>
/// 容器值
/// </summary>
public int ProcessCapacity = 1000;
}
}

View File

@@ -24,6 +24,7 @@ namespace YooAsset.Editor
private TextField _collectOutputField;
private Label _currentShaderCountField;
private Label _currentVariantCountField;
private SliderInt _processCapacitySlider;
private PopupField<string> _packageField;
public void CreateGUI()
@@ -72,6 +73,23 @@ namespace YooAsset.Editor
packageContainer.Add(_packageField);
}
// 容器值
_processCapacitySlider = root.Q<SliderInt>("ProcessCapacity");
_processCapacitySlider.SetValueWithoutNotify(ShaderVariantCollectorSettingData.Setting.ProcessCapacity);
#if !UNITY_2020_3_OR_NEWER
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
_processCapacitySlider.RegisterValueChangedCallback(evt =>
{
ShaderVariantCollectorSettingData.Setting.ProcessCapacity = _processCapacitySlider.value;
_processCapacitySlider.label = $"Capacity ({_processCapacitySlider.value})";
});
#else
_processCapacitySlider.RegisterValueChangedCallback(evt =>
{
ShaderVariantCollectorSettingData.Setting.ProcessCapacity = _processCapacitySlider.value;
});
#endif
_currentShaderCountField = root.Q<Label>("CurrentShaderCount");
_currentVariantCountField = root.Q<Label>("CurrentVariantCount");
@@ -103,7 +121,8 @@ namespace YooAsset.Editor
{
string savePath = ShaderVariantCollectorSettingData.Setting.SavePath;
string packageName = ShaderVariantCollectorSettingData.Setting.CollectPackage;
ShaderVariantCollector.Run(savePath, packageName, int.MaxValue, null);
int processCapacity = _processCapacitySlider.value;
ShaderVariantCollector.Run(savePath, packageName, processCapacity, null);
}
// 构建包裹相关

View File

@@ -1,10 +1,12 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;" />
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<ui:VisualElement name="CollectContainer">
<ui:TextField picking-mode="Ignore" label="文件保存路径" name="CollectOutput" style="height: 22px;" />
<ui:VisualElement name="PackageContainer" style="height: 24px;" />
<ui:VisualElement name="PackageContainer" style="height: 24px;">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;" />
</ui:VisualElement>
<ui:Label text="Current Shader Count" display-tooltip-when-elided="true" name="CurrentShaderCount" style="height: 20px; padding-left: 4px;" />
<ui:Label text="Current Variant Count" display-tooltip-when-elided="true" name="CurrentVariantCount" style="height: 20px; padding-left: 4px;" />
<ui:SliderInt picking-mode="Ignore" label="Capacity" value="9999" high-value="1000" name="ProcessCapacity" low-value="10" show-input-field="true" />
<ui:Button text="开始搜集" display-tooltip-when-elided="true" name="CollectButton" style="height: 50px; background-color: rgb(40, 106, 42); margin-top: 10px;" />
</ui:VisualElement>
</ui:UXML>

View File

@@ -8,11 +8,16 @@ namespace YooAsset
{
internal class AssetSystemImpl
{
private readonly List<BundleLoaderBase> _loaders = new List<BundleLoaderBase>(1000);
private readonly List<ProviderBase> _providers = new List<ProviderBase>(1000);
private readonly Dictionary<string, BundleLoaderBase> _loaderDic = new Dictionary<string, BundleLoaderBase>(5000);
private readonly List<BundleLoaderBase> _loaderList = new List<BundleLoaderBase>(5000);
private readonly Dictionary<string, ProviderBase> _providerDic = new Dictionary<string, ProviderBase>(5000);
private readonly List<ProviderBase> _providerList = new List<ProviderBase>(5000);
private readonly static Dictionary<string, SceneOperationHandle> _sceneHandles = new Dictionary<string, SceneOperationHandle>(100);
private static long _sceneCreateCount = 0;
private bool _isUnloadSafe = true;
private string _packageName;
private bool _simulationOnEditor;
private int _loadingMaxNumber;
@@ -39,7 +44,7 @@ namespace YooAsset
public void Update()
{
// 更新加载器
foreach (var loader in _loaders)
foreach (var loader in _loaderList)
{
loader.Update();
}
@@ -47,10 +52,11 @@ namespace YooAsset
// 更新资源提供者
// 注意:循环更新的时候,可能会扩展列表
// 注意:不能限制场景对象的加载
_isUnloadSafe = false;
int loadingCount = 0;
for (int i = 0; i < _providers.Count; i++)
for (int i = 0; i < _providerList.Count; i++)
{
var provider = _providers[i];
var provider = _providerList[i];
if (provider.IsSceneProvider())
{
provider.Update();
@@ -64,6 +70,7 @@ namespace YooAsset
loadingCount++;
}
}
_isUnloadSafe = true;
}
/// <summary>
@@ -71,17 +78,19 @@ namespace YooAsset
/// </summary>
public void DestroyAll()
{
foreach (var provider in _providers)
foreach (var provider in _providerList)
{
provider.Destroy();
}
_providers.Clear();
_providerList.Clear();
_providerDic.Clear();
foreach (var loader in _loaders)
foreach (var loader in _loaderList)
{
loader.Destroy(true);
}
_loaders.Clear();
_loaderList.Clear();
_loaderDic.Clear();
ClearSceneHandle();
DecryptionServices = null;
@@ -93,6 +102,12 @@ namespace YooAsset
/// </summary>
public void UnloadUnusedAssets()
{
if (_isUnloadSafe == false)
{
YooLogger.Warning("Can not unload unused assets when processing resource loading !");
return;
}
// 注意:资源包之间可能存在多层深层嵌套,需要多次循环释放。
int loopCount = 10;
for (int i = 0; i < loopCount; i++)
@@ -104,29 +119,33 @@ namespace YooAsset
{
if (_simulationOnEditor)
{
for (int i = _providers.Count - 1; i >= 0; i--)
for (int i = _providerList.Count - 1; i >= 0; i--)
{
if (_providers[i].CanDestroy())
var provider = _providerList[i];
if (provider.CanDestroy())
{
_providers[i].Destroy();
_providers.RemoveAt(i);
provider.Destroy();
_providerList.RemoveAt(i);
_providerDic.Remove(provider.ProviderGUID);
}
}
}
else
{
for (int i = _loaders.Count - 1; i >= 0; i--)
for (int i = _loaderList.Count - 1; i >= 0; i--)
{
BundleLoaderBase loader = _loaders[i];
BundleLoaderBase loader = _loaderList[i];
loader.TryDestroyAllProviders();
}
for (int i = _loaders.Count - 1; i >= 0; i--)
for (int i = _loaderList.Count - 1; i >= 0; i--)
{
BundleLoaderBase loader = _loaders[i];
BundleLoaderBase loader = _loaderList[i];
if (loader.CanDestroy())
{
string bundleName = loader.MainBundleInfo.Bundle.BundleName;
loader.Destroy(false);
_loaders.RemoveAt(i);
_loaderList.RemoveAt(i);
_loaderDic.Remove(bundleName);
}
}
}
@@ -137,17 +156,19 @@ namespace YooAsset
/// </summary>
public void ForceUnloadAllAssets()
{
foreach (var provider in _providers)
foreach (var provider in _providerList)
{
provider.Destroy();
}
foreach (var loader in _loaders)
foreach (var loader in _loaderList)
{
loader.Destroy(true);
}
_providers.Clear();
_loaders.Clear();
_providerList.Clear();
_providerDic.Clear();
_loaderList.Clear();
_loaderDic.Clear();
ClearSceneHandle();
// 注意:调用底层接口释放所有资源
@@ -182,7 +203,8 @@ namespace YooAsset
else
provider = new BundledSceneProvider(this, providerGUID, assetInfo, sceneMode, activateOnLoad, priority);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
_providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
}
var handle = provider.CreateHandle<SceneOperationHandle>();
@@ -213,7 +235,8 @@ namespace YooAsset
else
provider = new BundledAssetProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
_providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
}
return provider.CreateHandle<AssetOperationHandle>();
}
@@ -240,7 +263,8 @@ namespace YooAsset
else
provider = new BundledSubAssetsProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
_providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
}
return provider.CreateHandle<SubAssetsOperationHandle>();
}
@@ -267,7 +291,8 @@ namespace YooAsset
else
provider = new BundledRawFileProvider(this, providerGUID, assetInfo);
provider.InitSpawnDebugInfo();
_providers.Add(provider);
_providerList.Add(provider);
_providerDic.Add(providerGUID, provider);
}
return provider.CreateHandle<RawFileOperationHandle>();
}
@@ -338,19 +363,29 @@ namespace YooAsset
{
foreach (var provider in providers)
{
_providers.Remove(provider);
_providerList.Remove(provider);
_providerDic.Remove(provider.ProviderGUID);
}
}
internal bool CheckBundleDestroyed(int bundleID)
{
string bundleName = BundleServices.GetBundleName(bundleID);
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName);
if (loader == null)
return true;
return loader.IsDestroyed;
}
private BundleLoaderBase CreateAssetBundleLoaderInternal(BundleInfo bundleInfo)
{
// 如果加载器已经存在
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleInfo.Bundle.BundleName);
string bundleName = bundleInfo.Bundle.BundleName;
BundleLoaderBase loader = TryGetAssetBundleLoader(bundleName);
if (loader != null)
return loader;
// 新增下载需求
#if !UNITY_WEBGL
#if UNITY_WEBGL
if (bundleInfo.Bundle.IsRawFile)
loader = new RawBundleFileLoader(this, bundleInfo);
else
@@ -362,43 +397,30 @@ namespace YooAsset
loader = new AssetBundleFileLoader(this, bundleInfo);
#endif
_loaders.Add(loader);
_loaderList.Add(loader);
_loaderDic.Add(bundleName, loader);
return loader;
}
private BundleLoaderBase TryGetAssetBundleLoader(string bundleName)
{
BundleLoaderBase loader = null;
for (int i = 0; i < _loaders.Count; i++)
{
BundleLoaderBase temp = _loaders[i];
if (temp.MainBundleInfo.Bundle.BundleName.Equals(bundleName))
{
loader = temp;
break;
}
}
return loader;
if (_loaderDic.TryGetValue(bundleName, out BundleLoaderBase value))
return value;
else
return null;
}
private ProviderBase TryGetProvider(string providerGUID)
{
ProviderBase provider = null;
for (int i = 0; i < _providers.Count; i++)
{
ProviderBase temp = _providers[i];
if (temp.ProviderGUID.Equals(providerGUID))
{
provider = temp;
break;
}
}
return provider;
if (_providerDic.TryGetValue(providerGUID, out ProviderBase value))
return value;
else
return null;
}
#region
internal List<DebugProviderInfo> GetDebugReportInfos()
{
List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providers.Count);
foreach (var provider in _providers)
List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providerList.Count);
foreach (var provider in _providerList)
{
DebugProviderInfo providerInfo = new DebugProviderInfo();
providerInfo.AssetPath = provider.MainAssetInfo.AssetPath;
@@ -421,9 +443,9 @@ namespace YooAsset
internal List<BundleInfo> GetLoadedBundleInfos()
{
List<BundleInfo> result = new List<BundleInfo>(100);
foreach (var bundleLoader in _loaders)
foreach (var loader in _loaderList)
{
result.Add(bundleLoader.MainBundleInfo);
result.Add(loader.MainBundleInfo);
}
return result;
}

View File

@@ -100,7 +100,18 @@ namespace YooAsset
if (IsDone() == false)
return false;
return RefCount <= 0;
if (RefCount > 0)
return false;
// 检查引用链上的资源包是否已经全部销毁
// 注意:互相引用的资源包无法卸载!
foreach (var bundleID in MainBundleInfo.Bundle.ReferenceIDs)
{
if (Impl.CheckBundleDestroyed(bundleID) == false)
return false;
}
return true;
}
/// <summary>
@@ -123,14 +134,14 @@ namespace YooAsset
return;
// 销毁所有Providers
foreach (var provider in _providers)
{
provider.Destroy();
foreach (var provider in _providers)
{
provider.Destroy();
}
Impl.RemoveBundleProviders(_providers);
_providers.Clear();
}
// 从列表里移除Providers
Impl.RemoveBundleProviders(_providers);
_providers.Clear();
}

View File

@@ -13,7 +13,7 @@ namespace YooAsset
}
public override void Update()
{
DebugRecording();
DebugBeginRecording();
if (IsDone)
return;

View File

@@ -8,7 +8,7 @@ namespace YooAsset
}
public override void Update()
{
DebugRecording();
DebugBeginRecording();
if (IsDone)
return;

View File

@@ -23,7 +23,7 @@ namespace YooAsset
}
public override void Update()
{
DebugRecording();
DebugBeginRecording();
if (IsDone)
return;

View File

@@ -13,7 +13,7 @@ namespace YooAsset
}
public override void Update()
{
DebugRecording();
DebugBeginRecording();
if (IsDone)
return;

View File

@@ -221,6 +221,8 @@ namespace YooAsset
private TaskCompletionSource<object> _taskCompletionSource;
protected void InvokeCompletion()
{
DebugEndRecording();
// 进度百分百完成
Progress = 1f;
@@ -256,8 +258,7 @@ namespace YooAsset
public long LoadingTime { protected set; get; }
// 加载耗时统计
private bool _isRecording = false;
private Stopwatch _watch;
private Stopwatch _watch = null;
[Conditional("DEBUG")]
public void InitSpawnDebugInfo()
@@ -274,21 +275,21 @@ namespace YooAsset
}
[Conditional("DEBUG")]
protected void DebugRecording()
protected void DebugBeginRecording()
{
if (_isRecording == false)
if (_watch == null)
{
_isRecording = true;
_watch = Stopwatch.StartNew();
}
}
[Conditional("DEBUG")]
private void DebugEndRecording()
{
if (_watch != null)
{
if (IsDone)
{
LoadingTime = _watch.ElapsedMilliseconds;
_watch = null;
}
LoadingTime = _watch.ElapsedMilliseconds;
_watch = null;
}
}
#endregion

View File

@@ -13,7 +13,7 @@ namespace YooAsset
/// <summary>
/// 初始化时的验证级别
/// </summary>
public static EVerifyLevel InitVerifyLevel { set; get; } = EVerifyLevel.Low;
public static EVerifyLevel InitVerifyLevel { set; get; } = EVerifyLevel.Middle;
/// <summary>
/// 清空所有数据
@@ -23,6 +23,15 @@ namespace YooAsset
_cachedDic.Clear();
}
/// <summary>
/// 获取缓存文件总数
/// </summary>
public static int GetCachedFilesCount(string packageName)
{
var cache = GetOrCreateCache(packageName);
return cache.GetCachedFilesCount();
}
/// <summary>
/// 查询是否为验证文件
/// </summary>
@@ -37,6 +46,7 @@ namespace YooAsset
/// </summary>
public static void RecordFile(string packageName, string cacheGUID, PackageCache.RecordWrapper wrapper)
{
//YooLogger.Log($"Record file : {packageName} = {cacheGUID}");
var cache = GetOrCreateCache(packageName);
cache.Record(cacheGUID, wrapper);
}
@@ -69,35 +79,45 @@ namespace YooAsset
/// <summary>
/// 验证缓存文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingCacheFile(VerifyElement element, EVerifyLevel verifyLevel)
public static EVerifyResult VerifyingCacheFile(VerifyCacheElement element)
{
try
{
string infoFilePath = element.InfoFilePath;
if (File.Exists(infoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
if (InitVerifyLevel == EVerifyLevel.Low)
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
if (File.Exists(element.DataFilePath) == false)
return EVerifyResult.DataFileNotExisted;
return EVerifyResult.Succeed;
}
else
{
if (File.Exists(element.InfoFilePath) == false)
return EVerifyResult.InfoFileNotExisted;
// 解析信息文件获取验证数据
CacheFileInfo.ReadInfoFromFile(infoFilePath, out element.DataFileCRC, out element.DataFileSize);
// 解析信息文件获取验证数据
CacheFileInfo.ReadInfoFromFile(element.InfoFilePath, out element.DataFileCRC, out element.DataFileSize);
}
}
catch (Exception)
{
return EVerifyResult.Exception;
}
return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, verifyLevel);
return VerifyingInternal(element.DataFilePath, element.DataFileSize, element.DataFileCRC, InitVerifyLevel);
}
/// <summary>
/// 验证下载文件
/// 验证下载文件(子线程内操作)
/// </summary>
public static EVerifyResult VerifyingTempFile(PatchBundle patchBundle, EVerifyLevel verifyLevel)
public static EVerifyResult VerifyingTempFile(VerifyTempElement element)
{
return VerifyingInternal(patchBundle.TempDataFilePath, patchBundle.FileSize, patchBundle.FileCRC, verifyLevel);
return VerifyingInternal(element.TempDataFilePath, element.FileSize, element.FileCRC, EVerifyLevel.High);
}
/// <summary>
/// 验证记录文件
/// 验证记录文件(主线程内操作)
/// </summary>
public static EVerifyResult VerifyingRecordFile(string packageName, string cacheGUID)
{

View File

@@ -7,10 +7,15 @@ namespace YooAsset
public enum EVerifyLevel
{
/// <summary>
/// 验证文件大小
/// 验证文件存在
/// </summary>
Low,
/// <summary>
/// 验证文件大小
/// </summary>
Middle,
/// <summary>
/// 验证文件大小和CRC
/// </summary>

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a93a516506b2b5c4492fdefe26eb1175
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,175 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
internal class FindCacheFilesOperation : AsyncOperationBase
{
private enum ESteps
{
None,
FindPrepare,
FindBundleFiles,
FindRawFiles,
Done,
}
private readonly string _packageName;
private float _verifyStartTime;
private IEnumerator<DirectoryInfo> _bundleFilesEnumerator = null;
private IEnumerator<DirectoryInfo> _rawFilesEnumerator = null;
private ESteps _steps = ESteps.None;
/// <summary>
/// 需要验证的元素
/// </summary>
public readonly List<VerifyCacheElement> VerifyElements = new List<VerifyCacheElement>(5000);
public FindCacheFilesOperation(string packageName)
{
_packageName = packageName;
}
internal override void Start()
{
_steps = ESteps.FindPrepare;
_verifyStartTime = UnityEngine.Time.realtimeSinceStartup;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.FindPrepare)
{
// BundleFiles
{
string rootPath = PersistentHelper.GetCachedBundleFileFolderPath(_packageName);
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_bundleFilesEnumerator = directorieInfos.GetEnumerator();
}
}
// RawFiles
{
string rootPath = PersistentHelper.GetCachedRawFileFolderPath(_packageName);
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
if (rootDirectory.Exists)
{
var directorieInfos = rootDirectory.EnumerateDirectories();
_rawFilesEnumerator = directorieInfos.GetEnumerator();
}
}
_steps = ESteps.FindBundleFiles;
}
if (_steps == ESteps.FindBundleFiles)
{
if (UpdateFindBundleFiles())
return;
_steps = ESteps.FindRawFiles;
}
if (_steps == ESteps.FindRawFiles)
{
if (UpdateFindRawFiles())
return;
// 注意:总是返回成功
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Find cache files elapsed time {costTime:f1} seconds");
}
}
private bool UpdateFindBundleFiles()
{
if (_bundleFilesEnumerator == null)
return false;
bool isFindItem;
while (true)
{
isFindItem = _bundleFilesEnumerator.MoveNext();
if (isFindItem == false)
break;
var rootFoder = _bundleFilesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories();
foreach(var chidDirectory in childDirectories)
{
string cacheGUID = chidDirectory.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
// 创建验证元素类
string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyCacheElement element = new VerifyCacheElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
private bool UpdateFindRawFiles()
{
if (_rawFilesEnumerator == null)
return false;
bool isFindItem;
while (true)
{
isFindItem = _rawFilesEnumerator.MoveNext();
if (isFindItem == false)
break;
var rootFoder = _rawFilesEnumerator.Current;
var childDirectories = rootFoder.GetDirectories();
foreach (var chidDirectory in childDirectories)
{
string cacheGUID = chidDirectory.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
// 获取数据文件的后缀名
string dataFileExtension = string.Empty;
var fileInfos = chidDirectory.GetFiles();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.Extension == ".temp")
continue;
if (fileInfo.Name.StartsWith(YooAssetSettings.CacheBundleDataFileName))
{
dataFileExtension = fileInfo.Extension;
break;
}
}
// 创建验证元素类
string fileRootPath = chidDirectory.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}{dataFileExtension}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyCacheElement element = new VerifyCacheElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
VerifyElements.Add(element);
}
if (OperationSystem.IsBusy)
break;
}
return isFindItem;
}
}
}

View File

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

View File

@@ -6,14 +6,14 @@ using System.Threading;
namespace YooAsset
{
internal abstract class PackageVerifyOperation : AsyncOperationBase
internal abstract class VerifyCacheFilesOperation : AsyncOperationBase
{
public static PackageVerifyOperation CreateOperation(List<VerifyElement> elements)
public static VerifyCacheFilesOperation CreateOperation(List<VerifyCacheElement> elements)
{
#if UNITY_WEBGL
var operation = new PackageVerifyWithoutThreadOperation(elements);
var operation = new VerifyCacheFilesWithoutThreadOperation(elements);
#else
var operation = new PackageVerifyWithThreadOperation(elements);
var operation = new VerifyCacheFilesWithThreadOperation(elements);
#endif
return operation;
}
@@ -22,7 +22,7 @@ namespace YooAsset
/// <summary>
/// 本地缓存文件验证(线程版)
/// </summary>
internal class PackageVerifyWithThreadOperation : PackageVerifyOperation
internal class VerifyCacheFilesWithThreadOperation : VerifyCacheFilesOperation
{
private enum ESteps
{
@@ -33,8 +33,8 @@ namespace YooAsset
}
private readonly ThreadSyncContext _syncContext = new ThreadSyncContext();
private List<VerifyElement> _waitingList;
private List<VerifyElement> _verifyingList;
private List<VerifyCacheElement> _waitingList;
private List<VerifyCacheElement> _verifyingList;
private int _verifyMaxNum;
private int _verifyTotalCount;
private float _verifyStartTime;
@@ -42,7 +42,7 @@ namespace YooAsset
private int _failedCount;
private ESteps _steps = ESteps.None;
public PackageVerifyWithThreadOperation(List<VerifyElement> elements)
public VerifyCacheFilesWithThreadOperation(List<VerifyCacheElement> elements)
{
_waitingList = elements;
}
@@ -68,7 +68,7 @@ namespace YooAsset
if (_verifyMaxNum < 1)
_verifyMaxNum = 1;
_verifyingList = new List<VerifyElement>(_verifyMaxNum);
_verifyingList = new List<VerifyCacheElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify;
}
@@ -82,7 +82,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
float costTime = UnityEngine.Time.realtimeSinceStartup - _verifyStartTime;
YooLogger.Log($"Package verify elapsed time {costTime:f1} seconds");
YooLogger.Log($"Verify cache files elapsed time {costTime:f1} seconds");
}
for (int i = _waitingList.Count - 1; i >= 0; i--)
@@ -114,19 +114,19 @@ namespace YooAsset
return 1f;
return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
}
private bool BeginVerifyFileWithThread(VerifyElement element)
private bool BeginVerifyFileWithThread(VerifyCacheElement element)
{
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
}
private void VerifyInThread(object obj)
{
VerifyElement element = (VerifyElement)obj;
element.Result = CacheSystem.VerifyingCacheFile(element, CacheSystem.InitVerifyLevel);
VerifyCacheElement element = (VerifyCacheElement)obj;
element.Result = CacheSystem.VerifyingCacheFile(element);
_syncContext.Post(VerifyCallback, element);
}
private void VerifyCallback(object obj)
{
VerifyElement element = (VerifyElement)obj;
VerifyCacheElement element = (VerifyCacheElement)obj;
_verifyingList.Remove(element);
if (element.Result == EVerifyResult.Succeed)
@@ -139,12 +139,8 @@ namespace YooAsset
{
_failedCount++;
// 删除验证失败的缓存文件
if (Directory.Exists(element.FileRootPath))
{
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
Directory.Delete(element.FileRootPath, true);
}
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
element.DeleteFiles();
}
}
}
@@ -152,7 +148,7 @@ namespace YooAsset
/// <summary>
/// 本地缓存文件验证(非线程版)
/// </summary>
internal class PackageVerifyWithoutThreadOperation : PackageVerifyOperation
internal class VerifyCacheFilesWithoutThreadOperation : VerifyCacheFilesOperation
{
private enum ESteps
{
@@ -162,16 +158,16 @@ namespace YooAsset
Done,
}
private List<VerifyElement> _waitingList;
private List<VerifyElement> _verifyingList;
private List<VerifyCacheElement> _waitingList;
private List<VerifyCacheElement> _verifyingList;
private int _verifyMaxNum;
private int _verifyTotalCount;
private float _verifyStartTime;
private int _succeedCount;
private int _failedCount;
private ESteps _steps = ESteps.None;
public PackageVerifyWithoutThreadOperation(List<VerifyElement> elements)
public VerifyCacheFilesWithoutThreadOperation(List<VerifyCacheElement> elements)
{
_waitingList = elements;
}
@@ -193,7 +189,7 @@ namespace YooAsset
_verifyMaxNum = fileCount;
_verifyTotalCount = fileCount;
_verifyingList = new List<VerifyElement>(_verifyMaxNum);
_verifyingList = new List<VerifyCacheElement>(_verifyMaxNum);
_steps = ESteps.UpdateVerify;
}
@@ -233,9 +229,9 @@ namespace YooAsset
return 1f;
return (float)(_succeedCount + _failedCount) / _verifyTotalCount;
}
private void BeginVerifyFileWithoutThread(VerifyElement element)
private void BeginVerifyFileWithoutThread(VerifyCacheElement element)
{
element.Result = CacheSystem.VerifyingCacheFile(element, CacheSystem.InitVerifyLevel);
element.Result = CacheSystem.VerifyingCacheFile(element);
if (element.Result == EVerifyResult.Succeed)
{
_succeedCount++;
@@ -246,12 +242,8 @@ namespace YooAsset
{
_failedCount++;
// 删除验证失败的缓存文件
if (Directory.Exists(element.FileRootPath))
{
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
Directory.Delete(element.FileRootPath, true);
}
YooLogger.Warning($"Failed verify file and delete files : {element.FileRootPath}");
element.DeleteFiles();
}
}
}

View File

@@ -0,0 +1,136 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace YooAsset
{
internal abstract class VerifyTempFileOperation : AsyncOperationBase
{
public EVerifyResult VerifyResult { protected set; get; }
public static VerifyTempFileOperation CreateOperation(VerifyTempElement element)
{
#if UNITY_WEBGL
var operation = new VerifyTempFileWithoutThreadOperation(element);
#else
var operation = new VerifyTempFileWithThreadOperation(element);
#endif
return operation;
}
}
/// <summary>
/// 下载文件验证(线程版)
/// </summary>
internal class VerifyTempFileWithThreadOperation : VerifyTempFileOperation
{
private enum ESteps
{
None,
VerifyFile,
Waiting,
Done,
}
private readonly VerifyTempElement _element;
private ESteps _steps = ESteps.None;
public VerifyTempFileWithThreadOperation(VerifyTempElement element)
{
_element = element;
}
internal override void Start()
{
_steps = ESteps.VerifyFile;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.VerifyFile)
{
if (BeginVerifyFileWithThread(_element))
{
_steps = ESteps.Waiting;
}
}
}
private bool BeginVerifyFileWithThread(VerifyTempElement element)
{
return ThreadPool.QueueUserWorkItem(new WaitCallback(VerifyInThread), element);
}
private void VerifyInThread(object obj)
{
VerifyTempElement element = (VerifyTempElement)obj;
element.Result = CacheSystem.VerifyingTempFile(element);
DownloadSystem.SyncContext.Post(VerifyCallback, element);
}
private void VerifyCallback(object obj)
{
VerifyTempElement element = (VerifyTempElement)obj;
VerifyResult = element.Result;
if (element.Result == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed verify file : {element.TempDataFilePath} ! ErrorCode : {element.Result}";
}
}
}
/// <summary>
/// 下载文件验证(非线程版)
/// </summary>
internal class VerifyTempFileWithoutThreadOperation : VerifyTempFileOperation
{
private enum ESteps
{
None,
VerifyFile,
Done,
}
private readonly VerifyTempElement _element;
private ESteps _steps = ESteps.None;
public VerifyTempFileWithoutThreadOperation(VerifyTempElement element)
{
_element = element;
}
internal override void Start()
{
_steps = ESteps.VerifyFile;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.VerifyFile)
{
_element.Result = CacheSystem.VerifyingTempFile(_element);
VerifyResult = _element.Result;
if (_element.Result == EVerifyResult.Succeed)
{
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
else
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed verify file : {_element.TempDataFilePath} ! ErrorCode : {_element.Result}";
}
}
}
}
}

View File

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

View File

@@ -10,13 +10,14 @@ namespace YooAsset
private enum ESteps
{
None,
GetCacheFiles,
FindCacheFiles,
VerifyCacheFiles,
Done,
}
private readonly string _packageName;
private PackageVerifyOperation _packageVerifyOp;
private FindCacheFilesOperation _findCacheFilesOp;
private VerifyCacheFilesOperation _verifyCacheFilesOp;
private ESteps _steps = ESteps.None;
public PackageCachingOperation(string packageName)
@@ -25,56 +26,47 @@ namespace YooAsset
}
internal override void Start()
{
_steps = ESteps.GetCacheFiles;
_steps = ESteps.FindCacheFiles;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.GetCacheFiles)
if (_steps == ESteps.FindCacheFiles)
{
var elements = GetVerifyElements();
_packageVerifyOp = PackageVerifyOperation.CreateOperation(elements);
OperationSystem.StartOperation(_packageVerifyOp);
if (_findCacheFilesOp == null)
{
_findCacheFilesOp = new FindCacheFilesOperation(_packageName);
OperationSystem.StartOperation(_findCacheFilesOp);
}
Progress = _findCacheFilesOp.Progress;
if (_findCacheFilesOp.IsDone == false)
return;
_steps = ESteps.VerifyCacheFiles;
}
if (_steps == ESteps.VerifyCacheFiles)
{
Progress = _packageVerifyOp.Progress;
if (_packageVerifyOp.IsDone == false)
if (_verifyCacheFilesOp == null)
{
_verifyCacheFilesOp = VerifyCacheFilesOperation.CreateOperation(_findCacheFilesOp.VerifyElements);
OperationSystem.StartOperation(_verifyCacheFilesOp);
}
Progress = _verifyCacheFilesOp.Progress;
if (_verifyCacheFilesOp.IsDone == false)
return;
// 注意:总是返回成功
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
int totalCount = CacheSystem.GetCachedFilesCount(_packageName);
YooLogger.Log($"Package '{_packageName}' cached files count : {totalCount}");
}
}
private List<VerifyElement> GetVerifyElements()
{
string cacheFolderPath = PersistentHelper.GetCacheFolderPath(_packageName);
if (Directory.Exists(cacheFolderPath) == false)
return new List<VerifyElement>();
DirectoryInfo rootDirectory = new DirectoryInfo(cacheFolderPath);
DirectoryInfo[] fileFolders = rootDirectory.GetDirectories();
List<VerifyElement> result = new List<VerifyElement>(fileFolders.Length);
foreach (var fileFoder in fileFolders)
{
string cacheGUID = fileFoder.Name;
if (CacheSystem.IsCached(_packageName, cacheGUID))
continue;
string fileRootPath = fileFoder.FullName;
string dataFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleDataFileName}";
string infoFilePath = $"{fileRootPath}/{ YooAssetSettings.CacheBundleInfoFileName}";
VerifyElement element = new VerifyElement(_packageName, cacheGUID, fileRootPath, dataFilePath, infoFilePath);
result.Add(element);
}
return result;
}
}
}

View File

@@ -44,6 +44,14 @@ namespace YooAsset
_wrappers.Clear();
}
/// <summary>
/// 获取缓存文件总数
/// </summary>
public int GetCachedFilesCount()
{
return _wrappers.Count;
}
/// <summary>
/// 查询缓存记录
/// </summary>

View File

@@ -1,19 +1,23 @@

using System.IO;
namespace YooAsset
{
internal class VerifyElement
/// <summary>
/// 缓存文件验证元素
/// </summary>
internal class VerifyCacheElement
{
public string PackageName { private set; get; }
public string CacheGUID { private set; get; }
public string FileRootPath { private set; get; }
public string DataFilePath { private set; get; }
public string InfoFilePath { private set; get; }
public EVerifyResult Result;
public string DataFileCRC;
public long DataFileSize;
public VerifyElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath)
public VerifyCacheElement(string packageName, string cacheGUID, string fileRootPath, string dataFilePath, string infoFilePath)
{
PackageName = packageName;
CacheGUID = cacheGUID;
@@ -21,5 +25,37 @@ namespace YooAsset
DataFilePath = dataFilePath;
InfoFilePath = infoFilePath;
}
public void DeleteFiles()
{
if (File.Exists(DataFilePath))
{
File.Delete(DataFilePath);
}
if (File.Exists(InfoFilePath))
{
File.Delete(InfoFilePath);
}
}
}
/// <summary>
/// 下载文件验证元素
/// </summary>
internal class VerifyTempElement
{
public string TempDataFilePath { private set; get; }
public string FileCRC { private set; get; }
public long FileSize { private set; get; }
public EVerifyResult Result;
public VerifyTempElement(string tempDataFilePath, string fileCRC, long fileSize)
{
TempDataFilePath = tempDataFilePath;
FileCRC = fileCRC;
FileSize = fileSize;
}
}
}

View File

@@ -2,10 +2,16 @@
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine.Networking;
namespace YooAsset
{
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public delegate UnityWebRequest DownloadRequestDelegate(string url);
/// <summary>
/// 1. 保证每一时刻资源文件只存在一个下载器
/// 2. 保证下载器下载完成后立刻验证并缓存
@@ -16,11 +22,20 @@ namespace YooAsset
private static readonly Dictionary<string, DownloaderBase> _downloaderDic = new Dictionary<string, DownloaderBase>();
private static readonly List<string> _removeList = new List<string>(100);
/// <summary>
/// 线程同步
/// </summary>
public static ThreadSyncContext SyncContext { set; get; }
/// <summary>
/// 自定义下载器的请求委托
/// </summary>
public static DownloadRequestDelegate RequestDelegate = null;
/// <summary>
/// 自定义的证书认证实例
/// </summary>
public static CertificateHandler CertificateHandlerInstance;
public static CertificateHandler CertificateHandlerInstance = null;
/// <summary>
/// 启用断点续传功能文件的最小字节数
@@ -32,11 +47,23 @@ namespace YooAsset
/// </summary>
public static List<long> ClearFileResponseCodes { set; get; }
/// <summary>
/// 更新所有下载器
/// 初始化下载器
/// </summary>
public static void Initialize()
{
SyncContext = new ThreadSyncContext();
}
/// <summary>
/// 更新下载器
/// </summary>
public static void Update()
{
if (SyncContext != null)
SyncContext.Update();
// 更新下载器
_removeList.Clear();
foreach (var valuePair in _downloaderDic)
@@ -66,7 +93,12 @@ namespace YooAsset
}
_downloaderDic.Clear();
_removeList.Clear();
SyncContext = null;
RequestDelegate = null;
CertificateHandlerInstance = null;
BreakpointResumeFileSize = int.MaxValue;
ClearFileResponseCodes = null;
}
@@ -101,6 +133,18 @@ namespace YooAsset
}
}
/// <summary>
/// 创建一个新的网络请求
/// </summary>
public static UnityWebRequest NewRequest(string requestURL)
{
if (RequestDelegate != null)
return RequestDelegate.Invoke(requestURL);
var request = new UnityWebRequest(requestURL, UnityWebRequest.kHttpVerbGET);
return request;
}
/// <summary>
/// 获取下载器的总数
/// </summary>

View File

@@ -7,11 +7,13 @@ namespace YooAsset
{
None,
CheckTempFile,
WaitingCheckTempFile,
PrepareDownload,
CreateResumeDownloader,
CreateGeneralDownloader,
CheckDownload,
VerifyingFile,
VerifyTempFile,
WaitingVerifyTempFile,
CachingFile,
TryAgain,
Succeed,

View File

@@ -13,6 +13,8 @@ namespace YooAsset
private readonly string _tempFilePath;
private UnityWebRequest _webRequest = null;
private DownloadHandlerFileRange _downloadHandle = null;
private VerifyTempFileOperation _checkFileOp = null;
private VerifyTempFileOperation _verifyFileOp = null;
// 重置变量
private bool _isAbort = false;
@@ -34,17 +36,28 @@ namespace YooAsset
if (IsDone())
return;
// 检测本地临时文件
// 检测临时文件
if (_steps == ESteps.CheckTempFile)
{
var verifyResult = CacheSystem.VerifyingTempFile(_bundleInfo.Bundle, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
VerifyTempElement element = new VerifyTempElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_checkFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_checkFileOp);
_steps = ESteps.WaitingCheckTempFile;
}
// 等待检测结果
if (_steps == ESteps.WaitingCheckTempFile)
{
if (_checkFileOp.IsDone == false)
return;
if (_checkFileOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CachingFile;
}
else
{
if (verifyResult == EVerifyResult.FileOverflow)
if (_checkFileOp.VerifyResult == EVerifyResult.FileOverflow)
{
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
@@ -80,7 +93,7 @@ namespace YooAsset
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET);
_webRequest = DownloadSystem.NewRequest(_requestURL);
DownloadHandlerFile handler = new DownloadHandlerFile(_tempFilePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;
@@ -109,11 +122,11 @@ namespace YooAsset
}
#if UNITY_2019_4_OR_NEWER
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET);
_webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFile(_tempFilePath, true);
handler.removeFileOnAbort = false;
#else
_webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET);
_webRequest = DownloadSystem.NewRequest(_requestURL);
var handler = new DownloadHandlerFileRange(_tempFilePath, _bundleInfo.Bundle.FileSize, _webRequest);
_downloadHandle = handler;
#endif
@@ -188,7 +201,7 @@ namespace YooAsset
}
else
{
_steps = ESteps.VerifyingFile;
_steps = ESteps.VerifyTempFile;
}
// 释放下载器
@@ -196,21 +209,30 @@ namespace YooAsset
}
// 验证下载文件
if (_steps == ESteps.VerifyingFile)
if (_steps == ESteps.VerifyTempFile)
{
var verifyResult = CacheSystem.VerifyingTempFile(_bundleInfo.Bundle, EVerifyLevel.High);
if (verifyResult == EVerifyResult.Succeed)
VerifyTempElement element = new VerifyTempElement(_bundleInfo.Bundle.TempDataFilePath, _bundleInfo.Bundle.FileCRC, _bundleInfo.Bundle.FileSize);
_verifyFileOp = VerifyTempFileOperation.CreateOperation(element);
OperationSystem.StartOperation(_verifyFileOp);
_steps = ESteps.WaitingVerifyTempFile;
}
// 等待验证完成
if (_steps == ESteps.WaitingVerifyTempFile)
{
if (_verifyFileOp.IsDone == false)
return;
if (_verifyFileOp.Status == EOperationStatus.Succeed)
{
_steps = ESteps.CachingFile;
}
else
{
_lastError = $"Failed to verifying file : {_bundleInfo.Bundle.FileName}, ErrorCode : {verifyResult}";
// 注意:验证失败后删除文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
_lastError = _verifyFileOp.Error;
_steps = ESteps.TryAgain;
}
}
@@ -226,7 +248,7 @@ namespace YooAsset
long dataFileSize = _bundleInfo.Bundle.FileSize;
if (File.Exists(infoFilePath))
File.Delete(infoFilePath);
File.Delete(infoFilePath);
if (File.Exists(dataFilePath))
File.Delete(dataFilePath);

View File

@@ -29,7 +29,7 @@ namespace YooAsset
if (_webRequest == null)
{
URL = url;
_webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
_webRequest = DownloadSystem.NewRequest(URL);
DownloadHandlerBuffer handler = new DownloadHandlerBuffer();
_webRequest.downloadHandler = handler;
_webRequest.disposeDownloadHandlerOnDispose = true;

View File

@@ -39,7 +39,7 @@ namespace YooAsset
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
_webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
_webRequest = DownloadSystem.NewRequest(URL);
DownloadHandlerFile handler = new DownloadHandlerFile(savePath);
handler.removeFileOnAbort = true;
_webRequest.downloadHandler = handler;

View File

@@ -32,28 +32,36 @@ namespace YooAsset
private bool _isPause = false;
private long _lastDownloadBytes = 0;
private int _lastDownloadCount = 0;
private long _cachedDownloadBytes = 0;
private int _cachedDownloadCount = 0;
private ESteps _steps = ESteps.None;
/// <summary>
/// 下载文件总数量
/// 统计的下载文件总数量
/// </summary>
public int TotalDownloadCount { private set; get; }
/// <summary>
/// 下载文件的总大小
/// 统计的下载文件的总大小
/// </summary>
public long TotalDownloadBytes { private set; get; }
/// <summary>
/// 当前已经完成的下载总数量
/// </summary>
public int CurrentDownloadCount { private set; get; }
public int CurrentDownloadCount
{
get { return _lastDownloadCount; }
}
/// <summary>
/// 当前已经完成的下载总大小
/// </summary>
public long CurrentDownloadBytes { private set; get; }
public long CurrentDownloadBytes
{
get { return _lastDownloadBytes; }
}
/// <summary>
/// 当下载器结束(无论成功或失败)
@@ -120,7 +128,7 @@ namespace YooAsset
{
// 检测下载器结果
_removeList.Clear();
long downloadBytes = CurrentDownloadBytes;
long downloadBytes = _cachedDownloadBytes;
foreach (var downloader in _downloaders)
{
downloadBytes += (long)downloader.DownloadedBytes;
@@ -139,8 +147,8 @@ namespace YooAsset
// 下载成功
_removeList.Add(downloader);
CurrentDownloadCount++;
CurrentDownloadBytes += bundleInfo.Bundle.FileSize;
_cachedDownloadCount++;
_cachedDownloadBytes += bundleInfo.Bundle.FileSize;
}
// 移除已经完成的下载器(无论成功或失败)
@@ -150,10 +158,10 @@ namespace YooAsset
}
// 如果下载进度发生变化
if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != CurrentDownloadCount)
if (_lastDownloadBytes != downloadBytes || _lastDownloadCount != _cachedDownloadCount)
{
_lastDownloadBytes = downloadBytes;
_lastDownloadCount = CurrentDownloadCount;
_lastDownloadCount = _cachedDownloadCount;
Progress = (float)_lastDownloadBytes / TotalDownloadBytes;
OnDownloadProgressCallback?.Invoke(TotalDownloadCount, _lastDownloadCount, TotalDownloadBytes, _lastDownloadBytes);
}

View File

@@ -143,6 +143,7 @@ namespace YooAsset
patchBundle.IsRawFile = _buffer.ReadBool();
patchBundle.LoadMethod = _buffer.ReadByte();
patchBundle.Tags = _buffer.ReadUTF8Array();
patchBundle.ReferenceIDs = _buffer.ReadInt32Array();
Manifest.BundleList.Add(patchBundle);
patchBundle.ParseBundle(Manifest.PackageName, Manifest.OutputNameStyle);

View File

@@ -41,6 +41,11 @@ namespace YooAsset
/// </summary>
public string[] Tags;
/// <summary>
/// 引用该资源包的ID列表
/// </summary>
public int[] ReferenceIDs;
/// <summary>
/// 所属的包裹名称
@@ -66,8 +71,17 @@ namespace YooAsset
if (string.IsNullOrEmpty(_cachedDataFilePath) == false)
return _cachedDataFilePath;
string cacheRoot = PersistentHelper.GetCacheFolderPath(PackageName);
_cachedDataFilePath = $"{cacheRoot}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}";
string folderName = FileHash.Substring(0, 2);
if (IsRawFile)
{
string cacheRoot = PersistentHelper.GetCachedRawFileFolderPath(PackageName);
_cachedDataFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}{_fileExtension}";
}
else
{
string cacheRoot = PersistentHelper.GetCachedBundleFileFolderPath(PackageName);
_cachedDataFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleDataFileName}";
}
return _cachedDataFilePath;
}
}
@@ -83,8 +97,17 @@ namespace YooAsset
if (string.IsNullOrEmpty(_cachedInfoFilePath) == false)
return _cachedInfoFilePath;
string cacheRoot = PersistentHelper.GetCacheFolderPath(PackageName);
_cachedInfoFilePath = $"{cacheRoot}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}";
string folderName = FileHash.Substring(0, 2);
if (IsRawFile)
{
string cacheRoot = PersistentHelper.GetCachedRawFileFolderPath(PackageName);
_cachedInfoFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}";
}
else
{
string cacheRoot = PersistentHelper.GetCachedBundleFileFolderPath(PackageName);
_cachedInfoFilePath = $"{cacheRoot}/{folderName}/{CacheGUID}/{YooAssetSettings.CacheBundleInfoFileName}";
}
return _cachedInfoFilePath;
}
}
@@ -122,7 +145,7 @@ namespace YooAsset
}
/// <summary>
/// 文件名称(远端文件名和内置文件名)
/// 文件名称
/// </summary>
private string _fileName;
public string FileName
@@ -135,6 +158,20 @@ namespace YooAsset
}
}
/// <summary>
/// 文件后缀名
/// </summary>
private string _fileExtension;
public string FileExtension
{
get
{
if (string.IsNullOrEmpty(_fileExtension))
throw new Exception("Should never get here !");
return _fileExtension;
}
}
public PatchBundle()
{
@@ -146,7 +183,8 @@ namespace YooAsset
public void ParseBundle(string packageName, int nameStype)
{
PackageName = packageName;
_fileName = PatchManifestTools.CreateBundleFileName(nameStype, BundleName, FileHash, IsRawFile);
_fileExtension = PatchManifestTools.GetRemoteBundleFileExtension(BundleName);
_fileName = PatchManifestTools.GetRemoteBundleFileName(nameStype, BundleName, _fileExtension, FileHash);
}
/// <summary>

View File

@@ -220,6 +220,22 @@ namespace YooAsset
}
}
/// <summary>
/// 获取资源包名称
/// </summary>
public string GetBundleName(int bundleID)
{
if (bundleID >= 0 && bundleID < BundleList.Count)
{
var patchBundle = BundleList[bundleID];
return patchBundle.BundleName;
}
else
{
throw new Exception($"Invalid bundle id : {bundleID}");
}
}
/// <summary>
/// 尝试获取补丁资源
/// </summary>

View File

@@ -65,6 +65,7 @@ namespace YooAsset
buffer.WriteBool(patchBundle.IsRawFile);
buffer.WriteByte(patchBundle.LoadMethod);
buffer.WriteUTF8Array(patchBundle.Tags);
buffer.WriteInt32Array(patchBundle.ReferenceIDs);
}
// 写入文件流
@@ -127,6 +128,7 @@ namespace YooAsset
patchBundle.IsRawFile = buffer.ReadBool();
patchBundle.LoadMethod = buffer.ReadByte();
patchBundle.Tags = buffer.ReadUTF8Array();
patchBundle.ReferenceIDs = buffer.ReadInt32Array();
manifest.BundleList.Add(patchBundle);
}
}
@@ -155,21 +157,21 @@ namespace YooAsset
}
#endif
/// <summary>
/// 生成Bundle文件的正式名称
/// </summary>
public static string CreateBundleFileName(int nameStyle, string bundleName, string fileHash, bool isRawFile)
public static string GetRemoteBundleFileExtension(string bundleName)
{
string fileExtension = Path.GetExtension(bundleName);
return fileExtension;
}
public static string GetRemoteBundleFileName(int nameStyle, string bundleName, string fileExtension, string fileHash)
{
if (nameStyle == 1) //HashName
{
string fileExtension = isRawFile ? YooAssetSettingsData.Setting.RawBundleFileVariant : YooAssetSettingsData.Setting.AssetBundleFileVariant;
return StringUtility.Format("{0}.{1}", fileHash, fileExtension);
return StringUtility.Format("{0}{1}", fileHash, fileExtension);
}
else if (nameStyle == 4) //BundleName_HashName
{
string fileName = bundleName.Remove(bundleName.LastIndexOf('.'));
string fileExtension = isRawFile ? YooAssetSettingsData.Setting.RawBundleFileVariant : YooAssetSettingsData.Setting.AssetBundleFileVariant;
return StringUtility.Format("{0}_{1}.{2}", fileName, fileHash, fileExtension);
return StringUtility.Format("{0}_{1}{2}", fileName, fileHash, fileExtension);
}
else
{

View File

@@ -95,6 +95,10 @@ namespace YooAsset
{
throw new NotImplementedException();
}
string IBundleServices.GetBundleName(int bundleID)
{
throw new NotImplementedException();
}
bool IBundleServices.IsServicesValid()
{
return _activeManifest != null;

View File

@@ -330,6 +330,10 @@ namespace YooAsset
}
return result.ToArray();
}
string IBundleServices.GetBundleName(int bundleID)
{
return _activeManifest.GetBundleName(bundleID);
}
bool IBundleServices.IsServicesValid()
{
return _activeManifest != null;

View File

@@ -123,6 +123,10 @@ namespace YooAsset
}
return result.ToArray();
}
string IBundleServices.GetBundleName(int bundleID)
{
return _activeManifest.GetBundleName(bundleID);
}
bool IBundleServices.IsServicesValid()
{
return _activeManifest != null;

View File

@@ -13,6 +13,11 @@ namespace YooAsset
/// </summary>
BundleInfo[] GetAllDependBundleInfos(AssetInfo assetPath);
/// <summary>
/// 获取资源包名称
/// </summary>
string GetBundleName(int bundleID);
/// <summary>
/// 服务接口是否有效
/// </summary>

View File

@@ -5,26 +5,11 @@ namespace YooAsset
[CreateAssetMenu(fileName = "YooAssetSettings", menuName = "YooAsset/Create Settings")]
internal class YooAssetSettings : ScriptableObject
{
/// <summary>
/// AssetBundle文件的后缀名
/// </summary>
public string AssetBundleFileVariant = "bundle";
/// <summary>
/// 原生文件的后缀名
/// </summary>
public string RawBundleFileVariant = "rawfile";
/// <summary>
/// 清单文件名称
/// </summary>
public string PatchManifestFileName = "PatchManifest";
/// <summary>
/// 资源包名正规化(移除路径分隔符)
/// </summary>
public bool RegularBundleName = true;
/// <summary>
/// 清单文件头标记
@@ -39,9 +24,9 @@ namespace YooAsset
/// <summary>
/// 清单文件格式版本
/// </summary>
public const string PatchManifestFileVersion = "1.4.0";
public const string PatchManifestFileVersion = "1.4.6";
/// <summary>
/// 缓存的数据文件名称
/// </summary>
@@ -63,20 +48,9 @@ namespace YooAsset
/// </summary>
public const string ReportFileName = "BuildReport";
/// <summary>
/// Unity着色器资源包名称
/// </summary>
public const string UnityShadersBundleName = "unityshaders";
/// <summary>
/// 内置资源目录名称
/// </summary>
public const string StreamingAssetsBuildinFolder = "BuildinFiles";
/// <summary>
/// 忽略的文件类型
/// </summary>
public static readonly string[] IgnoreFileExtensions = { "", ".so", ".dll", ".cs", ".js", ".boo", ".meta", ".cginc", ".hlsl" };
}
}

View File

@@ -71,18 +71,5 @@ namespace YooAsset
{
return $"{Setting.PatchManifestFileName}_{packageName}.version";
}
/// <summary>
/// 获取着色器资源包全名称(包含后缀名)
/// </summary>
public static string GetUnityShadersBundleFullName(bool uniqueBundleName, string packageName)
{
string shareBundleName;
if (uniqueBundleName)
shareBundleName = $"{packageName.ToLower()}_{YooAssetSettings.UnityShadersBundleName}.{Setting.AssetBundleFileVariant}";
else
shareBundleName = $"{YooAssetSettings.UnityShadersBundleName}.{Setting.AssetBundleFileVariant}";
return shareBundleName.ToLower();
}
}
}

View File

@@ -84,6 +84,8 @@ namespace YooAsset
internal static class PersistentHelper
{
private const string CacheFolderName = "CacheFiles";
private const string CachedBundleFileFolder = "BundleFiles";
private const string CachedRawFileFolder = "RawFiles";
private const string ManifestFolderName = "ManifestFiles";
private const string AppFootPrintFileName = "ApplicationFootPrint.bytes";
@@ -120,12 +122,33 @@ namespace YooAsset
/// <summary>
/// 获取缓存文件夹路径
/// 获取缓存的BundleFile文件夹路径
/// </summary>
public static string GetCacheFolderPath(string packageName)
private readonly static Dictionary<string, string> _cachedBundleFileFolder = new Dictionary<string, string>(100);
public static string GetCachedBundleFileFolderPath(string packageName)
{
string root = PathHelper.MakePersistentLoadPath(CacheFolderName);
return $"{root}/{packageName}";
if (_cachedBundleFileFolder.TryGetValue(packageName, out string value) == false)
{
string root = PathHelper.MakePersistentLoadPath(CacheFolderName);
value = $"{root}/{packageName}/{CachedBundleFileFolder}";
_cachedBundleFileFolder.Add(packageName, value);
}
return value;
}
/// <summary>
/// 获取缓存的RawFile文件夹路径
/// </summary>
private readonly static Dictionary<string, string> _cachedRawFileFolder = new Dictionary<string, string>(100);
public static string GetCachedRawFileFolderPath(string packageName)
{
if (_cachedRawFileFolder.TryGetValue(packageName, out string value) == false)
{
string root = PathHelper.MakePersistentLoadPath(CacheFolderName);
value = $"{root}/{packageName}/{CachedRawFileFolder}";
_cachedRawFileFolder.Add(packageName, value);
}
return value;
}
/// <summary>

View File

@@ -34,8 +34,8 @@ namespace YooAsset
_driver.AddComponent<RemoteDebuggerInRuntime>();
#endif
// 初始化异步系统
OperationSystem.Initialize();
DownloadSystem.Initialize();
}
}
@@ -184,6 +184,14 @@ namespace YooAsset
DownloadSystem.CertificateHandlerInstance = instance;
}
/// <summary>
/// 设置下载系统参数,自定义下载请求
/// </summary>
public static void SetDownloadSystemUnityWebRequest(DownloadRequestDelegate requestDelegate)
{
DownloadSystem.RequestDelegate = requestDelegate;
}
/// <summary>
/// 设置异步系统参数,每帧执行消耗的最大时间切片(单位:毫秒)
/// </summary>

View File

@@ -10,7 +10,7 @@ public class PackEffectTexture : IPackRule
{
private const string PackDirectory = "Assets/Effect/Textures/";
string IPackRule.GetBundleName(PackRuleData data)
PackRuleResult IPackRule.GetPackRuleResult(PackRuleData data)
{
string assetPath = data.AssetPath;
if (assetPath.StartsWith(PackDirectory) == false)
@@ -18,6 +18,43 @@ public class PackEffectTexture : IPackRule
string assetName = Path.GetFileName(assetPath).ToLower();
string firstChar = assetName.Substring(0, 1);
return $"{PackDirectory}effect_texture_{firstChar}";
string bundleName = $"{PackDirectory}effect_texture_{firstChar}";
var packRuleResult = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return packRuleResult;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
[DisplayName("打包视频(自定义)")]
public class PackVideo : IPackRule
{
public PackRuleResult GetPackRuleResult(PackRuleData data)
{
string bundleName = RemoveExtension(data.AssetPath);
string fileExtension = Path.GetExtension(data.AssetPath);
fileExtension = fileExtension.Remove(0, 1);
PackRuleResult result = new PackRuleResult(bundleName, fileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return true;
}
private string RemoveExtension(string str)
{
if (string.IsNullOrEmpty(str))
return str;
int index = str.LastIndexOf(".");
if (index == -1)
return str;
else
return str.Remove(index); //"assets/config/test.unity3d" --> "assets/config/test"
}
}

View File

@@ -16,7 +16,7 @@ MonoBehaviour:
BuildMode: 0
BuildPackage: DefaultPackage
CompressOption: 2
OutputNameStyle: 4
OutputNameStyle: 1
CopyBuildinFileOption: 1
CopyBuildinFileTags:
EncyptionClassName: FileStreamEncryption

View File

@@ -1,22 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<root Version="2.2">
<root Version="2.3">
<Common AutoAddressable="True" UniqueBundleName="False" ShowPackageView="False" ShowEditorAlias="False" />
<Package PackageName="DefaultPackage" PackageDesc="">
<Group GroupName="battle" GroupDesc="" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Effect" CollectGUID="80d76514758554baaa96a9efffe9f3ef" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Entity" CollectGUID="4d7c84745db8e884f8020a8c5356e67c" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Audio" CollectGUID="306075fbe00b24251b6c889984a7a7d5" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Effect" CollectGUID="80d76514758554baaa96a9efffe9f3ef" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Entity" CollectGUID="4d7c84745db8e884f8020a8c5356e67c" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Audio" CollectGUID="306075fbe00b24251b6c889984a7a7d5" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group>
<Group GroupName="shader" GroupDesc="" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameArt/ShaderVariants" CollectGUID="00781758c26692e40a9634ddeac838be" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackShaderVariants" FilterRule="CollectShaderVariants" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameArt/ShaderVariants" CollectGUID="00781758c26692e40a9634ddeac838be" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackShaderVariants" FilterRule="CollectShaderVariants" UserData="" AssetTags="" />
</Group>
<Group GroupName="scene" GroupDesc="" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Scene" CollectGUID="6070eae1192f2994887f2983a177d503" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/Scene" CollectGUID="6070eae1192f2994887f2983a177d503" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group>
<Group GroupName="ugui" GroupDesc="" AssetTags="">
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIImage" CollectGUID="30c57db62bb02a24590e7046d3a9e33a" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIPanel" CollectGUID="12d33f33f3a55224c9c747d7bffa1c68" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UISprite" CollectGUID="01865ad6f7c806147b6cb37f2d83bc96" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackTopDirectory" FilterRule="CollectAll" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIImage" CollectGUID="30c57db62bb02a24590e7046d3a9e33a" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UIPanel" CollectGUID="12d33f33f3a55224c9c747d7bffa1c68" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackSeparately" FilterRule="CollectAll" UserData="" AssetTags="" />
<Collector CollectPath="Assets/Samples/Space Shooter/GameRes/UISprite" CollectGUID="01865ad6f7c806147b6cb37f2d83bc96" CollectType="MainAssetCollector" AddressRule="AddressByFileName" PackRule="PackTopDirectory" FilterRule="CollectAll" UserData="" AssetTags="" />
</Group>
</Package>
</root>

View File

@@ -32,6 +32,7 @@ MonoBehaviour:
PackRuleName: PackDirectory
FilterRuleName: CollectAll
AssetTags:
UserData:
- CollectPath: Assets/Samples/Space Shooter/GameRes/Entity
CollectorGUID: 4d7c84745db8e884f8020a8c5356e67c
CollectorType: 0
@@ -39,6 +40,7 @@ MonoBehaviour:
PackRuleName: PackDirectory
FilterRuleName: CollectAll
AssetTags:
UserData:
- CollectPath: Assets/Samples/Space Shooter/GameRes/Audio
CollectorGUID: 306075fbe00b24251b6c889984a7a7d5
CollectorType: 0
@@ -46,6 +48,7 @@ MonoBehaviour:
PackRuleName: PackDirectory
FilterRuleName: CollectAll
AssetTags:
UserData:
- GroupName: shader
GroupDesc:
AssetTags:
@@ -58,6 +61,7 @@ MonoBehaviour:
PackRuleName: PackShaderVariants
FilterRuleName: CollectShaderVariants
AssetTags:
UserData:
- GroupName: scene
GroupDesc:
AssetTags:
@@ -70,6 +74,7 @@ MonoBehaviour:
PackRuleName: PackSeparately
FilterRuleName: CollectAll
AssetTags:
UserData:
- GroupName: ugui
GroupDesc:
AssetTags:
@@ -82,6 +87,7 @@ MonoBehaviour:
PackRuleName: PackDirectory
FilterRuleName: CollectAll
AssetTags:
UserData:
- CollectPath: Assets/Samples/Space Shooter/GameRes/UIPanel
CollectorGUID: 12d33f33f3a55224c9c747d7bffa1c68
CollectorType: 0
@@ -89,6 +95,7 @@ MonoBehaviour:
PackRuleName: PackSeparately
FilterRuleName: CollectAll
AssetTags:
UserData:
- CollectPath: Assets/Samples/Space Shooter/GameRes/UISprite
CollectorGUID: 01865ad6f7c806147b6cb37f2d83bc96
CollectorType: 0
@@ -96,3 +103,4 @@ MonoBehaviour:
PackRuleName: PackTopDirectory
FilterRuleName: CollectAll
AssetTags:
UserData:

View File

@@ -12,4 +12,6 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 44454e58a49818040a1aef5799e71b30, type: 3}
m_Name: ShaderVariantCollectorSetting
m_EditorClassIdentifier:
SavePath: Assets/Samples/BassicSample/GameArt/ShaderVariants/MyShaderVariants.shadervariants
SavePath: Assets/ShaderVariants/MyShaderVariants.shadervariants
CollectPackage: DefaultPackage
ProcessCapacity: 1000

View File

@@ -3,21 +3,11 @@ using System.IO;
using System.Text;
using YooAsset;
public class EncryptionNone : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.Normal;
return result;
}
}
public class FileOffsetEncryption : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
if(fileInfo.BundleName.Contains("gameres_music"))
if (fileInfo.BundleName.Contains("_gameres_audio"))
{
int offset = 32;
byte[] fileData = File.ReadAllBytes(fileInfo.FilePath);
@@ -42,7 +32,8 @@ public class FileStreamEncryption : IEncryptionServices
{
public EncryptResult Encrypt(EncryptFileInfo fileInfo)
{
if (fileInfo.BundleName.Contains("gameres_music"))
// LoadFromStream
if (fileInfo.BundleName.Contains("_gameres_audio"))
{
var fileData = File.ReadAllBytes(fileInfo.FilePath);
for (int i = 0; i < fileData.Length; i++)
@@ -55,7 +46,22 @@ public class FileStreamEncryption : IEncryptionServices
result.EncryptedData = fileData;
return result;
}
else
// LoadFromFileOffset
if (fileInfo.BundleName.Contains("_gameres_uiimage"))
{
var fileData = File.ReadAllBytes(fileInfo.FilePath);
int offset = 32;
var temper = new byte[fileData.Length + offset];
Buffer.BlockCopy(fileData, 0, temper, offset, fileData.Length);
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.LoadFromFileOffset;
result.EncryptedData = temper;
return result;
}
// Normal
{
EncryptResult result = new EncryptResult();
result.LoadMethod = EBundleLoadMethod.Normal;

View File

@@ -2,6 +2,7 @@
// 作者Stark
//-------------------------------------
#if UNITY_ANDROID
/// <summary>
/// 为Github对开发者的友好采用自动补充UnityPlayerActivity.java文件的通用姿势满足各个开发者
/// </summary>
@@ -13,27 +14,64 @@ internal class AndroidPost : UnityEditor.Android.IPostGenerateGradleAndroidProje
path = path.Replace("\\", "/");
string untityActivityFilePath = $"{path}/src/main/java/com/unity3d/player/UnityPlayerActivity.java";
var readContent = System.IO.File.ReadAllLines(untityActivityFilePath);
string postContent = " //auto-gen-function\n" +
" public boolean CheckAssetExist(String filePath){\n" +
" android.content.res.AssetManager assetManager = getAssets();\n" +
" java.io.InputStream inputStream = null;\n" +
" try {\n" +
" inputStream = assetManager.open(filePath);\n" +
" if(null != inputStream)return true;\n" +
" }catch(java.io.IOException e) {\n" +
" e.printStackTrace();\n" +
" }finally{\n" +
" try {\n" +
" inputStream.close();\n" +
" } catch (java.io.IOException e) {\n" +
" e.printStackTrace();\n" +
" }\n" +
" }\n" +
" return false;\n" +
" }\n" +
string postContent =
" //auto-gen-function \n" +
" public boolean CheckAssetExist(String filePath) \n" +
" { \n" +
" android.content.res.AssetManager assetManager = getAssets(); \n" +
" try \n" +
" { \n" +
" java.io.InputStream inputStream = assetManager.open(filePath); \n" +
" if (null != inputStream) \n" +
" { \n" +
" inputStream.close(); \n" +
" return true; \n" +
" } \n" +
" } \n" +
" catch(java.io.IOException e) \n" +
" { \n" +
" e.printStackTrace(); \n" +
" } \n" +
" return false; \n" +
" } \n" +
"}";
if (!readContent[readContent.Length - 18].Contains("CheckAssetExist"))
if (CheckFunctionExist(readContent) == false)
readContent[readContent.Length - 1] = postContent;
System.IO.File.WriteAllLines(untityActivityFilePath, readContent);
}
}
private bool CheckFunctionExist(string[] contents)
{
for (int i = 0; i < contents.Length; i++)
{
if (contents[i].Contains("CheckAssetExist"))
{
return true;
}
}
return false;
}
}
#endif
/*
//auto-gen-function
public boolean CheckAssetExist(String filePath)
{
android.content.res.AssetManager assetManager = getAssets();
try
{
java.io.InputStream inputStream = assetManager.open(filePath);
if(null != inputStream)
{
inputStream.close();
return true;
}
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
return false;
}
*/

View File

@@ -1,10 +1,13 @@
//-------------------------------------
// 作者Stark
//-------------------------------------
using System.Collections.Generic;
using UnityEngine;
public sealed class StreamingAssetsHelper
{
private static readonly Dictionary<string, bool> _cacheData = new Dictionary<string, bool>(1000);
#if UNITY_ANDROID && !UNITY_EDITOR
private static AndroidJavaClass _unityPlayerClass;
public static AndroidJavaClass UnityPlayerClass
@@ -33,12 +36,22 @@ public sealed class StreamingAssetsHelper
/// </summary>
public static bool FileExists(string filePath)
{
return CurrentActivity.Call<bool>("CheckAssetExist", filePath);
if (_cacheData.TryGetValue(filePath, out bool result) == false)
{
result = CurrentActivity.Call<bool>("CheckAssetExist", filePath);
_cacheData.Add(filePath, result);
}
return result;
}
#else
public static bool FileExists(string filePath)
{
return System.IO.File.Exists(System.IO.Path.Combine(Application.streamingAssetsPath, filePath));
if (_cacheData.TryGetValue(filePath, out bool result) == false)
{
result = System.IO.File.Exists(System.IO.Path.Combine(Application.streamingAssetsPath, filePath));
_cacheData.Add(filePath, result);
}
return result;
}
#endif
}

View File

@@ -1,7 +1,7 @@
{
"name": "com.tuyoogame.yooasset",
"displayName": "YooAsset",
"version": "1.4.3-preview",
"version": "1.4.7",
"unity": "2019.4",
"description": "unity3d resources management system.",
"author": {

View File

@@ -1,6 +1,6 @@
# 资源构建
![image](./Image/AssetBuilder-img1.png)
![image](./Image/AssetBuilder-img1.jpg)
### 界面介绍
@@ -50,9 +50,7 @@
HashName哈希值
HashName_Extension哈希值+后缀名
HashName_BundleName_Extension资源包名+哈希值+后缀名
BundleName_HashName资源包名+哈希值
- **Copy Buildin File Option**
@@ -78,17 +76,23 @@
补丁包文件夹里包含补丁清单文件,资源包文件,构建报告文件等。
![image](./Image/AssetBuilder-img4.png)
![image](./Image/AssetBuilder-img2.jpg)
### 补丁清单
补丁清单是一个Json格式的文本文件。
补丁清单文件是上图中以PatchManifest开头命名的文件。
AssetList组记录的是主资源对象列表。
- PatchManifest_DefaultPackage_xxxxxx.hash
BundleList组记录的是资源包列表
记录了补丁清单文件的哈希值
![image](./Image/AssetBuilder-img2.png)
- PatchManifest_DefaultPackage_xxxxxx.json
该文件为Json文本格式主要用于开发者预览信息。
- PatchManifest_DefaultPackage_xxxxxx.bytes
该文件为二进制格式,主要用于程序内读取加载。
### Jenkins支持
@@ -109,10 +113,10 @@ private static void BuildInternal(BuildTarget buildTarget)
buildParameters.BuildPipeline = EBuildPipeline.BuiltinBuildPipeline;
buildParameters.BuildMode = EBuildMode.ForceRebuild;
buildParameters.PackageName = "DefaultPackage";
buildParameters.PackageVersion = "1.0.0";
buildParameters.PackageVersion = "1.0";
buildParameters.VerifyBuildingResult = true;
buildParameters.CompressOption = ECompressOption.LZ4;
buildParameters.OutputNameStyle = EOutputNameStyle.HashName_Extension;
buildParameters.OutputNameStyle = EOutputNameStyle.HashName;
buildParameters.CopyBuildinFileOption = ECopyBuildinFileOption.None;
// 执行构建
@@ -122,6 +126,10 @@ private static void BuildInternal(BuildTarget buildTarget)
{
Debug.Log($"构建成功 : {buildResult.OutputPackageDirectory}");
}
else
{
Debug.LogError($"构建失败 : {buildResult.FailedInfo}");
}
}
// 从构建命令里获取参数示例

View File

@@ -1,10 +1,14 @@
# 资源收集
![image](./Image/AssetCollector-img1.png)
![image](./Image/AssetCollector-img1.jpg)
左侧为分组列表,右侧为该分组的配置界面。
导出按钮可以将配置数据导出为XML文件导入按钮可以导入保存的XML文件。
导入按钮可以导入保存的XML文件。
导出按钮可以将配置数据导出为XML文件。
修复按钮:在配置里的文件夹挪动位置之后,可以通过该按钮按钮来修正。
**注意**该工具仅支持Unity2019.4+
@@ -13,11 +17,15 @@
- Show Packages
是否展示资源包列表视图。
- Show Editor Alias
是否显示为中文模式。
- Enable Addressable
启用可寻址资源定位系统。
- Unique Bundle Name
资源包名追加PackageName作为前缀。
@@ -36,10 +44,10 @@
//自定义扩展范例
public class DisableGroup : IActiveRule
{
public bool IsActiveGroup()
{
return false;
}
public bool IsActiveGroup()
{
return false;
}
}
````
@@ -83,18 +91,18 @@
- AddressByFileName 以文件名为定位地址。
- AddressByGrouperAndFileName 以分组名+文件名为定位地址。
- AddressByGrouperAndFileName 以分组名+文件名为定位地址。
- AddressByCollectorAndFileName 以收集器名+文件名为定位地址。
- AddressByFolderAndFileName 以文件夹名+文件名为定位地址。
````c#
//自定义扩展范例
public class AddressByFileName : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return Path.GetFileNameWithoutExtension(data.AssetPath);
}
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return Path.GetFileNameWithoutExtension(data.AssetPath);
}
}
````
@@ -102,21 +110,28 @@
打包规则,规则可以自定义扩展。下面是内置规则:
- PackSeparately 以收集文件路径作为资源包名,每个资源文件单独打包。
- PackDirectory 以收集文件所在的文件夹路径作为资源包名,该文件夹下所有文件打进一个资源包。
- PackTopDirectory 以收集器路径下顶级文件夹为资源包名,该文件夹下所有文件打进一个资源包。
- PackSeparately 以文件路径作为资源包名,每个资源文件单独打包。
- PackDirectory 以文件所在的文件夹路径作为资源包名,该文件夹下所有文件打进一个资源包。
- PackTopDirectory 以收集器下顶级文件夹为资源包名,该文件夹下所有文件打进一个资源包。
- PackCollector 以收集器路径作为资源包名,收集的所有文件打进一个资源包。
- PackGrouper 以分组名称作为资源包名,收集的所有文件打进一个资源包。
- PackGroup 以分组名称作为资源包名,收集的所有文件打进一个资源包。
- PackRawFile 目录下的资源文件会被处理为原生资源包。
````c#
//自定义扩展范例
public class PackDirectory : IPackRule
{
string IPackRule.GetBundleName(PackRuleData data)
{
return Path.GetDirectoryName(data.AssetPath); //"Assets/Config/test.txt" --> "Assets/Config"
}
PackRuleResult IPackRule.GetBundleName(PackRuleData data)
{
//"Assets/Config/test.txt" --> "Assets/Config"
string bundleName = Path.GetDirectoryName(data.AssetPath);
PackRuleResult result = new PackRuleResult(bundleName, DefaultPackRule.AssetBundleFileExtension);
return result;
}
bool IPackRule.IsRawFilePackRule()
{
return false;
}
}
````
@@ -133,13 +148,17 @@
//自定义扩展范例
public class CollectScene : IFilterRule
{
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".unity";
}
public bool IsCollectAsset(FilterRuleData data)
{
return Path.GetExtension(data.AssetPath) == ".unity";
}
}
````
- **UserData**
用户自定义数据可以帮助定制化AddressRule和PackRule。
- **AssetTags**
资源分类标签列表,该收集器下收集的资源会全部被打上该标签。

View File

@@ -4,19 +4,40 @@
如果是本地测试可以在本地创建一个WEB服务器然后将补丁包拷贝到WEB服务器下。
**按照游戏版本目录部署**
**部署目录**
在业务开发过程中,每个游戏版本实际都会创建一个SVN分支分支工程内每次构建的补丁包上传到对应的CDN目录下即可
在业务开发过程中,发版本之前都会创建一个SVN或GIT分支,分支工程为基础去构建APP
````
CDN
└─android
├─v1.0
├─v1.1
└─v2.0
├─v1.0APP版本
├─v1.1APP版本
└─v2.0APP版本
└─iphone
├─v1.0
├─v1.1
└─v2.0
├─v1.0APP版本
├─v1.1APP版本
└─v2.0APP版本
````
**APP版本说明**
v1.0 代表的是APP版本不是资源版本。在没有更换安装包的情况下不需要新增加APP版本目录。
例如我们游戏的当前APP版本是v1.0那么每次生成的补丁文件全部覆盖到v1.0的目录下即可。
下面的示例里一共上传过2次补丁包。第二次上传的补丁包会把第一次的版本记录文件PatchManifest_DefaultPackage.version覆盖掉。当我们想回退资源版本的时候把第一次生成的版本记录文件覆盖到同目录下即可。
````
v1.0(游戏版本)
├─PatchManifest_DefaultPackage.version
├─PatchManifest_DefaultPackage_2023-02-01-654.hash
├─PatchManifest_DefaultPackage_2023-02-01-654.bytes
├─PatchManifest_DefaultPackage_2023-02-12-789.hash
├─PatchManifest_DefaultPackage_2023-02-12-789.bytes
├─2bb5a28d37dabf27df8bc6a4706b8f80.bundle
├─2dbea9c3056c8839bc03d80a2aebd105.bundle
├─6e8c3003a64ead36a0bd2d5cdebfbcf4.bundle
...
````

View File

@@ -73,15 +73,17 @@ private class QueryStreamingAssetsFileServices : IQueryServices
{
public bool QueryStreamingAssets(string fileName)
{
// 注意使用了BetterStreamingAssets插件,使用前需要初始化该插件!
// StreamingAssetsHelper.cs是太空战机里提供的一个查询脚本。
string buildinFolderName = YooAssets.GetStreamingAssetBuildinFolderName();
return BetterStreamingAssets.FileExists($"{buildinFolderName}/{fileName}");
return StreamingAssetsHelper.FileExists($"{buildinFolderName}/{fileName}");
}
}
````
### 源代码解析
Package.InitializeAsync()方法解析。
- 编辑器模拟模式
每次启动调用EditorSimulateModeHelper.SimulateBuild()方法都会在底层执行一次模拟构建Simulate Build
@@ -90,11 +92,11 @@ private class QueryStreamingAssetsFileServices : IQueryServices
- 单机运行模式
在初始化的时候会直接读取内置清单文件StreamingAssets文件夹里的文件最后根据加载的清单去验证沙盒里缓存的文件
在初始化的时候会直接读取内置清单文件StreamingAssets文件夹里的文件最后初始化缓存系统
- 联机运行模式
在初始化的时候,会优先从沙盒里加载清单,如果沙盒里不存在,则会尝试加载内置清单并将其拷贝到沙盒里。最后根据加载的清单去验证沙盒里缓存的文件
在初始化的时候,会优先从沙盒里加载清单,如果沙盒里不存在,则会尝试加载内置清单并将其拷贝到沙盒里。最后初始化缓存系统
**注意**:如果沙盒清单和内置清单都不存在,初始化也会被判定为成功!

View File

@@ -16,8 +16,8 @@ private IEnumerator UpdateStaticVersion()
if (operation.Status == EOperationStatus.Succeed)
{
//更新成功
string PackageVersion = operation.PackageVersion;
Debug.Log($"Updated package Version : {PackageVersion}");
string packageVersion = operation.PackageVersion;
Debug.Log($"Updated package Version : {packageVersion}");
}
else
{
@@ -66,7 +66,7 @@ private IEnumerator UpdatePatchManifest()
用于下载更新资源标签指定的资源包文件。
- YooAssets.CreateBundleDownloader(string[] locations, int downloadingMaxNumber, int failedTryAgain, int timeout)
- YooAssets.CreateBundleDownloader(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
用于下载更新指定的资源列表依赖的资源包文件。
@@ -131,25 +131,37 @@ private IEnumerator Start()
// 如果获取远端资源版本失败,说明当前网络无连接。
// 在正常开始游戏之前,需要验证本地清单内容的完整性。
string packageVersion = package.GetPackageVersion();
var operation = package.CheckPackageContentsAsync(packageVersion);
var operation = package.PreDownloadPackageAsync(packageVersion);
yield return operation;
if (operation.Status == EOperationStatus.Succeed)
if (operation.Status != EOperationStatus.Succeed)
{
StartGame();
ShowMessageBox("请检查本地网络,有新的游戏内容需要更新!");
yield break;
}
else
int downloadingMaxNum = 10;
int failedTryAgain = 3;
int timeout = 60;
var downloader = operation.CreatePatchDownloader(downloadingMaxNum, failedTryAgain, timeout);
if (downloader.TotalDownloadCount > 0)
{
// 资源内容本地并不完整,需要提示玩家联网更新。
ShowMessageBox("请检查本地网络,有新的游戏内容需要更新!");
yield break;
}
// 开始游戏
StartGame();
}
}
````
### 源代码解析
Package.UpdatePackageManifestAsync()方法解析。
- 联机运行模式
UpdatePackageManifestAsync()为资源清单更新方法。该方法的内部实现原理如下:
通过传入的清单版本,优先比对当前激活清单的版本,如果相同就直接返回成功。如果有差异就从缓存里去查找匹配的清单,如果缓存里不存在,就去远端下载并保存到沙盒里。最后加载沙盒内匹配的清单文件。
![image](./Image/CodeTutorial2-img1.png)

View File

@@ -6,7 +6,9 @@
- LoadAssetAsync() 异步加载资源对象
- LoadSubAssetsSync() 同步加载子资源对象
- LoadSubAssetsAsync() 异步加载子资源对象
- LoadSceneSync() 同步加载场景
- LoadSceneAsync() 异步加载场景
- LoadRawFileSync() 同步获取原生文件
- LoadRawFileAsync() 异步获取原生文件
**统一约定**
@@ -152,6 +154,7 @@ IEnumerator Start()
yield return handle;
byte[] fileData = handle.GetRawFileData();
string fileText = handle.GetRawFileText();
string filePath = handle.GetRawFilePath();
}
````
@@ -160,7 +163,7 @@ IEnumerator Start()
通过资源标签来获取资源信息列表。
````c#
private GetAssetInfosByTag(string tag)
void GetAssetInfosByTag(string tag)
{
AssetInfo[] assetInfos = package.GetAssetInfos(tag);
foreach (var assetInfo in assetInfos)

View File

@@ -29,6 +29,10 @@ YooAsset依赖于ScriptBuildPipelineSBP在PackageManager里找到SBP插
Unity引擎不允许把场景文件和其它资源文件一起打包。
#### 问题WebGL平台运行时报错Failed to decompress data for the AssetBundle.
WebGL平台不支持资源文件加密。在构建选项里可以将加密方法设置为空
#### 问题ClearCacheWhenDirty参数没了吗
不是很必须的一个功能,已经移除了。可以使用以下方法代替:

View File

@@ -1,6 +1,6 @@
# 全局配置
![image](./Image/Settings-img1.png)
![image](./Image/Settings-img1.jpg)
通过右键创建配置文件Project窗体内右键 -> Create -> YooAsset -> Create Setting
@@ -8,7 +8,5 @@
配置说明:
- **Asset Bundle File Variant** : AssetBundle资源包后缀名
- **Raw File Variant** : 原生资源包后缀名
- **Patch Manifest File Name** : 补丁清单文件名称

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