Compare commits

..

81 Commits

Author SHA1 Message Date
何冠峰 2c68e5dfd5 Update CHANGELOG.md 2024-08-14 10:26:04 +08:00
何冠峰 1c6e54df21 Update package.json 2024-08-14 10:26:01 +08:00
hevinci a4d378894e fix #295 2024-05-10 10:45:57 +08:00
hevinci 9d5a90e8fa fix #276 2024-04-12 11:50:40 +08:00
hevinci bb1c64e444 合并2.x功能到1.5
1. 增加获取缓存文件信息的异步操作
2. 支持资源下载器合并
3. 新增资源导入器
2024-03-27 18:50:10 +08:00
hevinci 92ac301716 feat : support open harmony 2024-03-13 15:42:23 +08:00
hevinci 135d5b4f5b Update AssetBundleCollector.cs
打包忽略编辑器资产 LightmapParameters
2024-03-11 11:28:42 +08:00
hevinci 23931e5d58 update asset bundle collector
移除资源包名的空格
2024-02-20 09:48:32 +08:00
何冠峰 619b5dbdaf
Merge pull request #243 from ZensYue/main
去除文件名中的空格
2024-02-20 09:44:14 +08:00
e 3105521fa9 去除文件名中的空格 2024-02-19 22:20:34 +08:00
何冠峰 b180fd8fc6
Merge pull request #235 from JellyHoney/main
update DeserializeManifestOperation
2024-02-18 10:16:06 +08:00
JellyHoney 769678a4b5 update DeserializeManifestOperation
优化修改文件后缀耗时
2024-02-01 16:46:34 +08:00
hevinci f90530e9f4 fix #226 2024-01-02 10:49:46 +08:00
hevinci 2630a7e793 fix #177 2023-10-08 15:56:19 +08:00
hevinci 45b016ae0f fix #175 2023-10-07 18:56:30 +08:00
hevinci c8ab0a43dd Update CHANGELOG.md 2023-10-07 16:31:13 +08:00
hevinci 9457a804b4 Update package.json 2023-10-07 16:31:09 +08:00
hevinci 880d498618 update download system
webgl平台支持下载器
2023-09-27 16:54:44 +08:00
hevinci ca89113c67 Update CHANGELOG.md 2023-09-26 18:54:25 +08:00
hevinci 29d840b168 Update package.json 2023-09-26 18:54:19 +08:00
hevinci 41d1586109 fix #96 2023-09-26 18:51:00 +08:00
hevinci 8d6a1d0066 Update CHANGELOG.md 2023-09-25 19:09:20 +08:00
hevinci bdfaaa0973 Update package.json 2023-09-25 19:09:11 +08:00
hevinci 30854e4b93 update asset settings
可以自定义设置参数DefaultYooFolderName
2023-09-25 18:25:34 +08:00
hevinci 54d89d957a update package system 2023-09-25 18:19:58 +08:00
hevinci ade97605f9 update asset bundle collector
增加了AddressDisable规则
2023-09-25 18:19:48 +08:00
hevinci bcb6443300 update asset bundle builder 2023-09-25 17:59:31 +08:00
hevinci 11386a7ec2 fix #161 2023-09-25 16:57:35 +08:00
hevinci 6fc45a758c fix #171 2023-09-25 16:21:02 +08:00
hevinci dcdf41b7c2 fix #96 2023-09-25 15:38:49 +08:00
hevinci 1aaf569396 fix #167 2023-09-25 15:08:43 +08:00
hevinci 101960f6d8 fix #163 2023-09-25 12:18:55 +08:00
hevinci 49b188964c fix #169 2023-09-25 11:38:01 +08:00
何冠峰 5539d81c93
Merge pull request #153 from michael811125/main
判断分组不激活时,则不进行 CheckConfigError 的检测
2023-09-01 14:07:11 +08:00
MichaelO ac3154e2ae 判断分组不激活时,则不进行 CheckConfigError 的检测 2023-09-01 13:43:03 +08:00
何冠峰 880b6d429d
Merge pull request #151 from michael811125/main
加入 ExtdBuildTasks 进行 SBP 扩展,修复 Sprite 打包冗馀问题 (猫佬方案) + typo error
2023-08-28 10:30:58 +08:00
MichaelO 070db961fc corrected typo error 2023-08-26 15:03:12 +08:00
MichaelO 96ef379668
Merge branch 'tuyoogame:main' into main 2023-08-25 20:48:08 +08:00
hevinci 697a87721f Update CHANGELOG.md 2023-08-25 20:39:53 +08:00
hevinci 09cf93d852 Update package.json 2023-08-25 20:39:46 +08:00
hevinci 8725821a27 update download system 2023-08-25 20:15:58 +08:00
MichaelO 7ad8651ca0 加入 ExtdBuildTasks 进行 SBP 扩展,修复 Sprite 打包冗馀问题 2023-08-25 19:48:02 +08:00
hevinci a2e57c6e90 update operation system 2023-08-25 17:37:49 +08:00
hevinci 6d37bca2a9 update asset bundle builder 2023-08-25 17:37:34 +08:00
hevinci 8471bb0f9a update asset bundle builder
暂时移除xxHash
2023-08-25 17:19:57 +08:00
何冠峰 05cb57db09
Merge pull request #150 from yingnierxiao/main
优化打包速度,提示编辑器启动速度,md5替换xxhash,速度提升一倍以上
2023-08-25 15:17:49 +08:00
yingnierxiao 064e9a1aa3 优化打包速度,提示编辑器启动速度,md5替换xxhash,速度提升一倍以上 2023-08-25 14:53:59 +08:00
hevinci a618b6cf9e update asset bundle reporter 2023-08-18 18:31:15 +08:00
何冠峰 e3e810e702
Merge pull request #134 from gepengmiss/main
bundle viewer 功能扩展
2023-08-18 17:58:43 +08:00
hevinci b4f0d6bab8 fix #138 2023-08-18 17:40:55 +08:00
hevinci 44cb4168cf update asset bundle collector 2023-08-17 22:13:31 +08:00
hevinci 559ed95999 update asset bundle collector
增加在配置错误的时候警示提示。
2023-08-17 21:53:51 +08:00
hevinci b766df1d31 update shader variant collector 2023-08-17 21:18:21 +08:00
hevinci 057ff6b22b fix #130 2023-08-17 21:05:21 +08:00
hevinci 995b0c8050 update space shooter 2023-08-15 18:19:07 +08:00
hevinci a2d4691f04 update package system
IQueryServices接口变更为IBuildinQueryServices
2023-08-14 12:27:43 +08:00
hevinci ab2d7d4724 update operation system
Operation状态增加Processing处理中状态
2023-08-11 16:20:38 +08:00
hevinci 9b4abf86b6 update runtime code
可寻址模式默认支持通过资源路径加载。
2023-08-09 20:15:55 +08:00
hevinci 0331b7b6e3 update editor code 2023-08-09 20:15:33 +08:00
hevinci e31799e78b Update CHANGELOG.md 2023-07-28 17:32:44 +08:00
hevinci a8405eea6d Update package.json 2023-07-28 17:32:38 +08:00
hevinci c11f072c50 update asset system 2023-07-28 17:17:23 +08:00
YGP bd080eb19b modify bundleViewer func 2023-07-27 16:12:21 +08:00
YGP ef231e213e modify bundleViewer func 2023-07-27 16:06:09 +08:00
YGP a5900b5f99 ignore 2023-07-27 16:04:59 +08:00
hevinci b22bbd4e27 update editor code 2023-07-25 18:48:32 +08:00
hevinci 664866b627 update space shooter 2023-07-25 18:38:02 +08:00
hevinci ad9bdc6574 update download system 2023-07-25 18:37:43 +08:00
hevinci b93b993951 update package system 2023-07-20 14:28:22 +08:00
hevinci cb2cb4e556 update package system 2023-07-20 11:27:56 +08:00
hevinci ab32bd390d update space shooter 2023-07-20 11:08:52 +08:00
hevinci b34374adfa update runtime code 2023-07-20 11:08:38 +08:00
hevinci b53b6a4246 update runtime code 2023-07-20 11:08:28 +08:00
hevinci 191fbff768 update package system
增加对清单激活的检测
2023-07-19 18:18:03 +08:00
hevinci e8a4ddf331 update runtime code 2023-07-19 17:48:26 +08:00
hevinci aee6e2d2f8 update space shooter 2023-07-19 17:06:35 +08:00
hevinci b737b20602 update runtime code
支持开发者资源分发和加载
2023-07-19 17:06:20 +08:00
hevinci b5df539392 update package system
增加对UpdatePackageManifestOperation参数的检测
2023-07-19 15:57:34 +08:00
hevinci 36c53e5d94 update space shooter 2023-07-19 14:34:51 +08:00
hevinci 15ce6b8c8c update runtime code 2023-07-19 14:34:43 +08:00
hevinci 19aa82c131 update editor code 2023-07-19 11:22:59 +08:00
92 changed files with 1521 additions and 600 deletions

17
.gitignore vendored
View File

@ -10,8 +10,23 @@
/[Ll]ogs/
/[Mm]emoryCaptures/
/Bundles/
/ProjectSettings/
/App/
/yoo/
/Assets/StreamingAssets
/Assets/StreamingAssets.meta
/Assets/Samples
/Assets/Samples.meta
/Packages
/UserSettings
# Asset meta data should only be ignored when the corresponding asset is also ignored
!/[Aa]ssets/**/*.meta
# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*

View File

@ -2,6 +2,152 @@
All notable changes to this package will be documented in this file.
## [1.5.8] - 2024-8-14
### Fixed
- (#175) 修复了Mac平台URL路径有空格的情况会报Malformed URL错误。
- (#177) 修复了加载一个地址的主资源或子资源之后无法再加载另一种的问题。
- (#266) 修复了资源系统遍历IsBusy次数过多导致过多的耗时的问题。
- (#276) 修复了HostPlayMode模式下如果内置清单是最新版本每次运行都会触发拷贝行为。
- (#295) 修复了在安卓平台,华为和三星真机上有极小概率加载资源包失败 : Unable to open archive file。
### Added
- 新增资源导入器。
- 新增获取缓存文件信息的方法。
### Changed
- 支持鸿蒙操作系统。
- 支持资源下载器合并。
## [1.5.7] - 2023-10-07
### Changed
- WebGL平台支持创建下载器。
## [1.5.6-preview] - 2023-09-26
### Fixed
- (#172) 修复包裹初始化后package的状态不正确的问题。
## [1.5.5-preview] - 2023-09-25
### Fixed
- (#96) 修复了异步操作任务的完成回调在业务层触发异常时无法正常完成的问题。
- (#156) 修复了多个Package存在时服务器请求地址请求顺序不对的问题。
- (#163) 修复了Unity2019版本编译报错的问题。
- (#167) 修复了初始化时每次都会提示文件验证失败日志。
- (#171) 修复了IsNeedDownloadFromRemote里缺少判断依赖的资源是否下载 。
### Added
- 资源收集器里增加了AddressDisable规则。
- 资源收集器里FilterRuleData结构体增加了多个备选字段。
```c#
public struct FilterRuleData
{
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
}
```
### Changed
- 可以设置自定义参数DefaultYooFolderName。
- 资源配置界面的分组不激活时,不再进行配置检测。
- SBP构建管线增加新构建参数用于修复图集资源冗余问题。
```c#
public class SBPBuildParameters
{
/// <summary>
/// 修复图集资源冗余问题
/// </summary>
public bool FixSpriteAtlasRedundancy = false;
}
```
## [1.5.4-preview] - 2023-08-25
优化了资源清单文件构建速度极大提升构建体验感谢yingnierxiao同学
### Fixed
- (#130) 修复了打包路径无效问题bug
- (#138) 修复了Unity不支持的格式的原生文件会报warning
### Added
- 新增了IBuildinQueryServices 接口。
### Changed
- 在开启可寻址模式下,默认支持通过资源路径加载资源对象。
- 优化了资源收集界面,增加了配置相关的警示提示。
- 优化了资源报告界面增加了BundleView界面里的builtin资源的列表显示。
- IQueryServices接口变更为IBuildinQueryServices接口
- EOperationStatus增加了正在处理的状态。
```c#
public enum EOperationStatus
{
None,
Processing,
Succeed,
Failed
}
```
## [1.5.3-preview] - 2023-07-28
### Fixed
- 修复了Unity2020以下版本的编辑器提示找不到"autoLoadAssetBundle"的编译错误。
### Added
- 新增了支持开发者分发资源的功能。
```c#
public interface IQueryServices
{
/// <summary>
/// 查询应用程序里的内置资源是否存在
/// </summary>
bool QueryStreamingAssets(string packageName, string fileName);
/// <summary>
/// 查询是否为开发者分发的资源
/// </summary>
bool QueryDeliveryFiles(string packageName, string fileName);
/// <summary>
/// 获取开发者分发的资源信息
/// </summary>
DeliveryFileInfo GetDeliveryFileInfo(string packageName, string fileName);
}
```
### Changed
- 针对资源清单更新方法传入参数的合法性检测。
- 编辑器下针对激活的资源清单有效性的检测。
## [1.5.2-preview] - 2023-07-18
重新设计了对WebGL平台的支持新增加了专属模式WebPlayMode

View File

@ -22,7 +22,7 @@ namespace YooAsset.Editor
/// </summary>
public static string GetDefaultStreamingAssetsRoot()
{
return $"{Application.dataPath}/StreamingAssets/{YooAssetSettings.DefaultYooFolderName}/";
return $"{Application.dataPath}/StreamingAssets/{YooAssetSettingsData.Setting.DefaultYooFolderName}/";
}
}
}

View File

@ -1,215 +0,0 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Animations;
namespace YooAsset.Editor
{
public static class AssetBundleBuilderTools
{
/// <summary>
/// 检测所有损坏的预制体文件
/// </summary>
public static void CheckCorruptionPrefab(List<string> searchDirectorys)
{
if (searchDirectorys.Count == 0)
throw new Exception("路径列表不能为空!");
// 获取所有资源列表
int checkCount = 0;
int invalidCount = 0;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.Prefab, searchDirectorys.ToArray());
foreach (string assetPath in findAssets)
{
UnityEngine.Object prefab = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object));
if (prefab == null)
{
invalidCount++;
Debug.LogError($"发现损坏预制件:{assetPath}");
}
EditorTools.DisplayProgressBar("检测预制件文件是否损坏", ++checkCount, findAssets.Length);
}
EditorTools.ClearProgressBar();
if (invalidCount == 0)
Debug.Log($"没有发现损坏预制件");
}
/// <summary>
/// 检测所有动画控制器的冗余状态
/// </summary>
public static void FindRedundantAnimationState(List<string> searchDirectorys)
{
if (searchDirectorys.Count == 0)
throw new Exception("路径列表不能为空!");
// 获取所有资源列表
int checkCount = 0;
int findCount = 0;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.RuntimeAnimatorController, searchDirectorys.ToArray());
foreach (string assetPath in findAssets)
{
AnimatorController animator= AssetDatabase.LoadAssetAtPath<AnimatorController>(assetPath);
if (FindRedundantAnimationState(animator))
{
findCount++;
Debug.LogWarning($"发现冗余的动画控制器:{assetPath}");
}
EditorTools.DisplayProgressBar("检测冗余的动画控制器", ++checkCount, findAssets.Length);
}
EditorTools.ClearProgressBar();
if (findCount == 0)
Debug.Log($"没有发现冗余的动画控制器");
else
AssetDatabase.SaveAssets();
}
/// <summary>
/// 清理所有材质球的冗余属性
/// </summary>
public static void ClearMaterialUnusedProperty(List<string> searchDirectorys)
{
if (searchDirectorys.Count == 0)
throw new Exception("路径列表不能为空!");
// 获取所有资源列表
int checkCount = 0;
int removedCount = 0;
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.Material, searchDirectorys.ToArray());
foreach (string assetPath in findAssets)
{
Material mat = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
if (ClearMaterialUnusedProperty(mat))
{
removedCount++;
Debug.LogWarning($"材质球已被处理:{assetPath}");
}
EditorTools.DisplayProgressBar("清理冗余的材质球", ++checkCount, findAssets.Length);
}
EditorTools.ClearProgressBar();
if (removedCount == 0)
Debug.Log($"没有发现冗余的材质球");
else
AssetDatabase.SaveAssets();
}
/// <summary>
/// 清理无用的材质球属性
/// </summary>
private static bool ClearMaterialUnusedProperty(Material mat)
{
bool removeUnused = false;
SerializedObject so = new SerializedObject(mat);
SerializedProperty sp = so.FindProperty("m_SavedProperties");
sp.Next(true);
do
{
if (sp.isArray == false)
continue;
for (int i = sp.arraySize - 1; i >= 0; --i)
{
var p1 = sp.GetArrayElementAtIndex(i);
if (p1.isArray)
{
for (int ii = p1.arraySize - 1; ii >= 0; --ii)
{
var p2 = p1.GetArrayElementAtIndex(ii);
var val = p2.FindPropertyRelative("first");
if (mat.HasProperty(val.stringValue) == false)
{
Debug.Log($"Material {mat.name} remove unused property : {val.stringValue}");
p1.DeleteArrayElementAtIndex(ii);
removeUnused = true;
}
}
}
else
{
var val = p1.FindPropertyRelative("first");
if (mat.HasProperty(val.stringValue) == false)
{
Debug.Log($"Material {mat.name} remove unused property : {val.stringValue}");
sp.DeleteArrayElementAtIndex(i);
removeUnused = true;
}
}
}
}
while (sp.Next(false));
so.ApplyModifiedProperties();
return removeUnused;
}
/// <summary>
/// 查找动画控制器里冗余的动画状态机
/// </summary>
private static bool FindRedundantAnimationState(AnimatorController animatorController)
{
if (animatorController == null)
return false;
string assetPath = AssetDatabase.GetAssetPath(animatorController);
// 查找使用的状态机名称
List<string> usedStateNames = new List<string>();
foreach (var layer in animatorController.layers)
{
foreach (var state in layer.stateMachine.states)
{
usedStateNames.Add(state.state.name);
}
}
List<string> allLines = new List<string>();
List<int> stateIndexList = new List<int>();
using (StreamReader reader = File.OpenText(assetPath))
{
string content;
while (null != (content = reader.ReadLine()))
{
allLines.Add(content);
if (content.StartsWith("AnimatorState:"))
{
stateIndexList.Add(allLines.Count - 1);
}
}
}
List<string> allStateNames = new List<string>();
foreach (var index in stateIndexList)
{
for (int i = index; i < allLines.Count; i++)
{
string content = allLines[i];
content = content.Trim();
if (content.StartsWith("m_Name"))
{
string[] splits = content.Split(':');
string name = splits[1].TrimStart(' '); //移除前面的空格
allStateNames.Add(name);
break;
}
}
}
bool foundRedundantState = false;
foreach (var stateName in allStateNames)
{
if (usedStateNames.Contains(stateName) == false)
{
Debug.LogWarning($"发现冗余的动画文件:{assetPath}={stateName}");
foundRedundantState = true;
}
}
return foundRedundantState;
}
}
}

View File

@ -28,6 +28,11 @@ namespace YooAsset.Editor
/// 缓存服务器端口
/// </summary>
public int CacheServerPort;
/// <summary>
/// 修复图集资源冗余问题
/// </summary>
public bool FixSpriteAtlasRedundancy = false;
}
/// <summary>

View File

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

View File

@ -0,0 +1,68 @@
using System.Collections.Generic;
using UnityEditor.Build.Content;
using UnityEngine.U2D;
using UnityEditor.Build.Pipeline.Injector;
using UnityEditor.Build.Pipeline.Interfaces;
using UnityEngine;
using System.Linq;
namespace UnityEditor.Build.Pipeline.Tasks
{
/// <summary>
/// Ref https://zhuanlan.zhihu.com/p/586918159
/// </summary>
public class RemoveSpriteAtlasRedundancy : IBuildTask
{
public int Version => 1;
[InjectContext]
IBundleWriteData writeDataParam;
public ReturnCode Run()
{
#if UNITY_2020_3_OR_NEWER
BundleWriteData writeData = (BundleWriteData)writeDataParam;
// 图集引用的精灵图片集合
HashSet<GUID> spriteGuids = new HashSet<GUID>();
foreach (var pair in writeData.FileToObjects)
{
foreach (ObjectIdentifier objectIdentifier in pair.Value)
{
var assetPath = AssetDatabase.GUIDToAssetPath(objectIdentifier.guid);
var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(SpriteAtlas))
{
var spritePaths = AssetDatabase.GetDependencies(assetPath, false);
foreach (string spritePath in spritePaths)
{
GUID spriteGuild = AssetDatabase.GUIDFromAssetPath(spritePath);
spriteGuids.Add(spriteGuild);
}
}
}
}
// 移除图集引用的精力图片对象
foreach (var pair in writeData.FileToObjects)
{
List<ObjectIdentifier> objectIdentifiers = pair.Value;
for (int i = objectIdentifiers.Count - 1; i >= 0; i--)
{
ObjectIdentifier objectIdentifier = objectIdentifiers[i];
if (spriteGuids.Contains(objectIdentifier.guid))
{
if (objectIdentifier.localIdentifierInFile == 2800000)
{
// 删除图集散图的冗余纹理
objectIdentifiers.RemoveAt(i);
}
}
}
}
#endif
return ReturnCode.Success;
}
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: fe50795c51a46884088139b840c1557f
guid: f01d5c82be95c8f4b93aeefc0454ae5c
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -9,7 +9,7 @@ namespace UnityEditor.Build.Pipeline.Tasks
{
public static class SBPBuildTasks
{
public static IList<IBuildTask> Create(string builtInShaderBundleName)
public static IList<IBuildTask> Create(bool fixSpriteAtlasRedundancy, string builtInShaderBundleName)
{
var buildTasks = new List<IBuildTask>();
@ -33,6 +33,8 @@ namespace UnityEditor.Build.Pipeline.Tasks
// Packing
buildTasks.Add(new GenerateBundlePacking());
if (fixSpriteAtlasRedundancy)
buildTasks.Add(new RemoveSpriteAtlasRedundancy());
buildTasks.Add(new UpdateBundleObjectLayout());
buildTasks.Add(new GenerateBundleCommands());
buildTasks.Add(new GenerateSubAssetPathMaps());

View File

@ -33,7 +33,7 @@ namespace YooAsset.Editor
// 开始构建
IBundleBuildResults buildResults;
var buildParameters = buildParametersContext.GetSBPBuildParameters();
var taskList = SBPBuildTasks.Create(buildMapContext.Command.ShadersBundleName);
var taskList = SBPBuildTasks.Create(buildParametersContext.Parameters.SBPParameters.FixSpriteAtlasRedundancy, buildMapContext.Command.ShadersBundleName);
ReturnCode exitCode = ContentPipeline.BuildAssetBundles(buildParameters, buildContent, out buildResults, taskList);
if (exitCode < 0)
{

View File

@ -40,7 +40,12 @@ namespace YooAsset.Editor
manifest.OutputNameStyle = (int)buildParameters.OutputNameStyle;
manifest.PackageName = buildParameters.PackageName;
manifest.PackageVersion = buildParameters.PackageVersion;
// 填充资源包集合
manifest.BundleList = GetAllPackageBundle(context);
CacheBundleIDs(manifest);
// 填充主资源集合
manifest.AssetList = GetAllPackageAsset(context, manifest);
// 更新Unity内置资源包的引用关系
@ -147,7 +152,7 @@ namespace YooAsset.Editor
packageAsset.AssetPath = assetInfo.AssetPath;
packageAsset.AssetGUID = buildMapContext.Command.IncludeAssetGUID ? assetInfo.AssetGUID : string.Empty;
packageAsset.AssetTags = assetInfo.AssetTags.ToArray();
packageAsset.BundleID = GetAssetBundleID(assetInfo.BundleName, manifest);
packageAsset.BundleID = GetCachedBundleID(assetInfo.BundleName);
packageAsset.DependIDs = GetAssetBundleDependIDs(packageAsset.BundleID, assetInfo, manifest);
result.Add(packageAsset);
}
@ -156,12 +161,12 @@ namespace YooAsset.Editor
}
private int[] GetAssetBundleDependIDs(int mainBundleID, BuildAssetInfo assetInfo, PackageManifest manifest)
{
List<int> result = new List<int>();
HashSet<int> result = new HashSet<int>();
foreach (var dependAssetInfo in assetInfo.AllDependAssetInfos)
{
if (dependAssetInfo.HasBundleName())
{
int bundleID = GetAssetBundleID(dependAssetInfo.BundleName, manifest);
int bundleID = GetCachedBundleID(dependAssetInfo.BundleName);
if (mainBundleID != bundleID)
{
if (result.Contains(bundleID) == false)
@ -171,15 +176,6 @@ namespace YooAsset.Editor
}
return result.ToArray();
}
private int GetAssetBundleID(string bundleName, PackageManifest manifest)
{
for (int index = 0; index < manifest.BundleList.Count; index++)
{
if (manifest.BundleList[index].BundleName == bundleName)
return index;
}
throw new Exception($"Not found bundle name : {bundleName}");
}
/// <summary>
/// 更新Unity内置资源包的引用关系
@ -212,7 +208,7 @@ namespace YooAsset.Editor
List<string> conflictAssetPathList = dependBundles.Intersect(shaderBundleReferenceList).ToList();
if (conflictAssetPathList.Count > 0)
{
List<int> newDependIDs = new List<int>(packageAsset.DependIDs);
HashSet<int> newDependIDs = new HashSet<int>(packageAsset.DependIDs);
if (newDependIDs.Contains(shaderBundleId) == false)
newDependIDs.Add(shaderBundleId);
packageAsset.DependIDs = newDependIDs.ToArray();
@ -226,7 +222,7 @@ namespace YooAsset.Editor
// 更新资源包标签
var packageBundle = manifest.BundleList[shaderBundleId];
List<string> newTags = new List<string>(packageBundle.Tags);
HashSet<string> newTags = new HashSet<string>(packageBundle.Tags);
foreach (var tag in tagTemps)
{
if (newTags.Contains(tag) == false)
@ -251,22 +247,21 @@ namespace YooAsset.Editor
private readonly Dictionary<string, int> _cachedBundleID = new Dictionary<string, int>(10000);
private readonly Dictionary<string, string[]> _cachedBundleDepends = new Dictionary<string, string[]>(10000);
private void CacheBundleIDs(PackageManifest manifest)
{
UnityEngine.Debug.Assert(manifest.BundleList.Count != 0, "Manifest bundle list is empty !");
for (int index = 0; index < manifest.BundleList.Count; index++)
{
string bundleName = manifest.BundleList[index].BundleName;
_cachedBundleID.Add(bundleName, index);
}
}
private void UpdateScriptPipelineReference(PackageManifest manifest, TaskBuilding_SBP.BuildResultContext buildResultContext)
{
int progressValue;
int totalCount = manifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
int bundleID = GetAssetBundleID(packageBundle.BundleName, manifest);
_cachedBundleID.Add(packageBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
@ -283,7 +278,11 @@ namespace YooAsset.Editor
var depends = buildResultContext.Results.BundleInfos[packageBundle.BundleName].Dependencies;
_cachedBundleDepends.Add(packageBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
int pro = ++progressValue;
if (pro % 100 == 0)
{
EditorTools.DisplayProgressBar("缓存资源包依赖列表", pro, totalCount);
}
}
EditorTools.ClearProgressBar();
@ -291,7 +290,11 @@ namespace YooAsset.Editor
foreach (var packageBundle in manifest.BundleList)
{
packageBundle.ReferenceIDs = GetBundleRefrenceIDs(manifest, packageBundle);
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
int pro = ++progressValue;
if (pro % 100 == 0)
{
EditorTools.DisplayProgressBar("计算资源包引用关系", pro, totalCount);
}
}
EditorTools.ClearProgressBar();
}
@ -300,17 +303,6 @@ namespace YooAsset.Editor
int progressValue;
int totalCount = manifest.BundleList.Count;
// 缓存资源包ID
_cachedBundleID.Clear();
progressValue = 0;
foreach (var packageBundle in manifest.BundleList)
{
int bundleID = GetAssetBundleID(packageBundle.BundleName, manifest);
_cachedBundleID.Add(packageBundle.BundleName, bundleID);
EditorTools.DisplayProgressBar("缓存资源包索引", ++progressValue, totalCount);
}
EditorTools.ClearProgressBar();
// 缓存资源包依赖
_cachedBundleDepends.Clear();
progressValue = 0;
@ -324,7 +316,11 @@ namespace YooAsset.Editor
var depends = buildResultContext.UnityManifest.GetDirectDependencies(packageBundle.BundleName);
_cachedBundleDepends.Add(packageBundle.BundleName, depends);
EditorTools.DisplayProgressBar("缓存资源包依赖列表", ++progressValue, totalCount);
int pro = ++progressValue;
if (pro % 100 == 0)
{
EditorTools.DisplayProgressBar("缓存资源包依赖列表", pro, totalCount);
}
}
EditorTools.ClearProgressBar();
@ -333,8 +329,12 @@ namespace YooAsset.Editor
foreach (var packageBundle in manifest.BundleList)
{
packageBundle.ReferenceIDs = GetBundleRefrenceIDs(manifest, packageBundle);
int pro = ++progressValue;
if (pro % 100 == 0)
{
EditorTools.DisplayProgressBar("计算资源包引用关系", ++progressValue, totalCount);
}
}
EditorTools.ClearProgressBar();
}
@ -354,7 +354,7 @@ namespace YooAsset.Editor
}
}
List<int> result = new List<int>();
HashSet<int> result = new HashSet<int>();
foreach (var bundleName in referenceList)
{
int bundleID = GetCachedBundleID(bundleName);

View File

@ -33,7 +33,7 @@ namespace YooAsset.Editor
Dictionary<string, BuildAssetInfo> allBuildAssetInfoDic = new Dictionary<string, BuildAssetInfo>(1000);
// 1. 检测配置合法性
AssetBundleCollectorSettingData.Setting.CheckConfigError();
AssetBundleCollectorSettingData.Setting.CheckPackageConfigError(packageName);
// 2. 获取所有收集器收集的资源
var collectResult = AssetBundleCollectorSettingData.Setting.GetPackageAssets(buildMode, packageName);

View File

@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
@ -130,7 +131,7 @@ namespace YooAsset.Editor
{
var buildMode = buildParametersContext.Parameters.BuildMode;
if (buildMode == EBuildMode.DryRunBuild || buildMode == EBuildMode.SimulateBuild)
return "00000000000000000000000000000000"; //32位
return GetFilePathTempHash(filePath);
else
return HashUtility.FileMD5(filePath);
}
@ -150,5 +151,32 @@ namespace YooAsset.Editor
else
return FileUtility.GetFileSize(filePath);
}
protected string GetFilePathTempHash(string filePath)
{
byte[] bytes = Encoding.UTF8.GetBytes(filePath);
return HashUtility.BytesMD5(bytes);
// 注意:在文件路径的哈希值冲突的情况下,可以使用下面的方法
//return $"{HashUtility.BytesMD5(bytes)}-{Guid.NewGuid():N}";
}
protected long GetBundleTempSize(BuildBundleInfo bundleInfo)
{
long tempSize = 0;
var assetPaths = bundleInfo.GetAllMainAssetPaths();
foreach (var assetPath in assetPaths)
{
long size = FileUtility.GetFileSize(assetPath);
tempSize += size;
}
if (tempSize == 0)
{
string message = $"Bundle temp size is zero, check bundle main asset list : {bundleInfo.BundleName}";
throw new Exception(message);
}
return tempSize;
}
}
}

View File

@ -166,7 +166,7 @@ namespace YooAsset.Editor
string[] findAssets = EditorTools.FindAssets(EAssetSearchType.All, collectDirectory);
foreach (string assetPath in findAssets)
{
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(group, assetPath))
{
if (result.ContainsKey(assetPath) == false)
{
@ -183,7 +183,7 @@ namespace YooAsset.Editor
else
{
string assetPath = CollectPath;
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(assetPath))
if (IsValidateAsset(assetPath, isRawFilePackRule) && IsCollectAsset(group, assetPath))
{
var collectAssetInfo = CreateCollectAssetInfo(command, group, assetPath, isRawFilePackRule);
result.Add(assetPath, collectAssetInfo);
@ -204,6 +204,12 @@ namespace YooAsset.Editor
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (string.IsNullOrEmpty(address))
continue;
if (address.StartsWith("Assets/") || address.StartsWith("assets/"))
throw new Exception($"The address can not set asset path in collector : {CollectPath} \nAssetPath: {assetPath}");
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else
@ -245,7 +251,7 @@ namespace YooAsset.Editor
// 忽略编辑器下的类型资源
Type assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
if (assetType == typeof(LightingDataAsset))
if (assetType == typeof(LightingDataAsset) || assetType == typeof(LightmapParameters))
return false;
// 检测原生文件是否合规
@ -288,11 +294,11 @@ namespace YooAsset.Editor
return true;
}
private bool IsCollectAsset(string assetPath)
private bool IsCollectAsset(AssetBundleCollectorGroup group, string assetPath)
{
// 根据规则设置过滤资源文件
IFilterRule filterRuleInstance = AssetBundleCollectorSettingData.GetFilterRuleInstance(FilterRuleName);
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath));
return filterRuleInstance.IsCollectAsset(new FilterRuleData(assetPath, CollectPath, group.GroupName, UserData));
}
private string GetAddress(CollectCommand command, AssetBundleCollectorGroup group, string assetPath)
{
@ -336,10 +342,12 @@ namespace YooAsset.Editor
List<string> result = new List<string>(depends.Length);
foreach (string assetPath in depends)
{
// 注意:排除主资源对象
if (assetPath == mainAssetPath)
continue;
if (IsValidateAsset(assetPath, false))
{
// 注意:排除主资源对象
if (assetPath != mainAssetPath)
result.Add(assetPath);
}
}

View File

@ -44,6 +44,9 @@ namespace YooAsset.Editor
if (AssetBundleCollectorSettingData.HasActiveRuleName(ActiveRuleName) == false)
throw new Exception($"Invalid {nameof(IActiveRule)} class type : {ActiveRuleName} in group : {GroupName}");
// 当分组不是激活状态时,直接不进行检测
if (ActiveRuleName == nameof(DisableGroup)) return;
foreach (var collector in Collectors)
{
collector.CheckConfigError();
@ -103,6 +106,9 @@ namespace YooAsset.Editor
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (string.IsNullOrEmpty(address))
continue;
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else

View File

@ -83,6 +83,9 @@ namespace YooAsset.Editor
{
string address = collectInfoPair.Value.Address;
string assetPath = collectInfoPair.Value.AssetPath;
if (string.IsNullOrEmpty(address))
continue;
if (addressTemper.TryGetValue(address, out var existed) == false)
addressTemper.Add(address, assetPath);
else

View File

@ -61,9 +61,18 @@ namespace YooAsset.Editor
}
/// <summary>
/// 检测配置错误
/// 检测包裹配置错误
/// </summary>
public void CheckConfigError()
public void CheckPackageConfigError(string packageName)
{
var package = GetPackage(packageName);
package.CheckConfigError();
}
/// <summary>
/// 检测所有配置错误
/// </summary>
public void CheckAllPackageConfigError()
{
foreach (var package in Packages)
{
@ -72,9 +81,9 @@ namespace YooAsset.Editor
}
/// <summary>
/// 修复配置错误
/// 修复所有配置错误
/// </summary>
public bool FixConfigError()
public bool FixAllPackageConfigError()
{
bool isFixed = false;
foreach (var package in Packages)
@ -92,17 +101,9 @@ namespace YooAsset.Editor
/// </summary>
public List<string> GetPackageAllTags(string packageName)
{
foreach (var package in Packages)
{
if (package.PackageName == packageName)
{
var package = GetPackage(packageName);
return package.GetAllTags();
}
}
Debug.LogWarning($"Not found package : {packageName}");
return new List<string>();
}
/// <summary>
/// 获取包裹收集的资源文件
@ -110,21 +111,27 @@ namespace YooAsset.Editor
public CollectResult GetPackageAssets(EBuildMode buildMode, string packageName)
{
if (string.IsNullOrEmpty(packageName))
throw new Exception("Build package name is null or mepty !");
throw new Exception("Build package name is null or empty !");
foreach (var package in Packages)
{
if (package.PackageName == packageName)
{
var package = GetPackage(packageName);
CollectCommand command = new CollectCommand(buildMode, packageName,
EnableAddressable, LocationToLower, IncludeAssetGUID, UniqueBundleName);
CollectResult collectResult = new CollectResult(command);
collectResult.SetCollectAssets(package.GetAllCollectAssets(command));
return collectResult;
}
}
throw new Exception($"Not found collector pacakge : {packageName}");
/// <summary>
/// 获取包裹类
/// </summary>
public AssetBundleCollectorPackage GetPackage(string packageName)
{
foreach (var package in Packages)
{
if (package.PackageName == packageName)
return package;
}
throw new Exception($"Not found package : {packageName}");
}
}
}

View File

@ -94,7 +94,8 @@ namespace YooAsset.Editor
typeof(AddressByFileName),
typeof(AddressByFilePath),
typeof(AddressByFolderAndFileName),
typeof(AddressByGroupAndFileName)
typeof(AddressByGroupAndFileName),
typeof(AddressDisable)
};
var customTypes = EditorTools.GetAssignableTypes(typeof(IAddressRule));
@ -161,7 +162,7 @@ namespace YooAsset.Editor
/// </summary>
public static void FixFile()
{
bool isFixed = Setting.FixConfigError();
bool isFixed = Setting.FixAllPackageConfigError();
if (isFixed)
{
IsDirty = true;

View File

@ -26,6 +26,7 @@ namespace YooAsset.Editor
private List<RuleDisplayName> _filterRuleList;
private Button _settingsButton;
private VisualElement _helpBoxContainer;
private VisualElement _setting1Container;
private VisualElement _setting2Container;
private Toggle _showPackageToogle;
@ -82,6 +83,9 @@ namespace YooAsset.Editor
visualAsset.CloneTree(root);
// 警示栏
_helpBoxContainer = root.Q("HelpBoxContainer");
// 公共设置相关
_settingsButton = root.Q<Button>("SettingsButton");
_settingsButton.clicked += SettingsBtn_clicked;
@ -328,6 +332,26 @@ namespace YooAsset.Editor
_uniqueBundleNameToogle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.UniqueBundleName);
_showEditorAliasToggle.SetValueWithoutNotify(AssetBundleCollectorSettingData.Setting.ShowEditorAlias);
// 警示框
#if UNITY_2020_3_OR_NEWER
_helpBoxContainer.Clear();
if (_enableAddressableToogle.value && _locationToLowerToogle.value)
{
var helpBox = new HelpBox("无法同时开启[Enable Addressable]选项和[Location To Lower]选项", HelpBoxMessageType.Error);
_helpBoxContainer.Add(helpBox);
}
if (AssetBundleCollectorSettingData.Setting.Packages.Count > 1 && _uniqueBundleNameToogle.value == false)
{
var helpBox = new HelpBox("检测到当前配置存在多个Package建议开启[Unique Bundle Name]选项", HelpBoxMessageType.Warning);
_helpBoxContainer.Add(helpBox);
}
if (_helpBoxContainer.childCount > 0)
_helpBoxContainer.style.display = DisplayStyle.Flex;
else
_helpBoxContainer.style.display = DisplayStyle.None;
#endif
// 设置栏
if (_showSettings)
{
_setting1Container.style.display = DisplayStyle.Flex;

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" editor-extension-mode="True">
<uie:Toolbar name="Toolbar" style="display: flex; flex-direction: row-reverse;">
<ui:Button text="Save" display-tooltip-when-elided="true" name="SaveButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
<ui:Button text="导出" display-tooltip-when-elided="true" name="ExportButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
@ -6,6 +6,7 @@
<ui:Button text="修复" display-tooltip-when-elided="true" name="FixButton" style="width: 50px; background-color: rgb(56, 147, 58);" />
</uie:Toolbar>
<ui:VisualElement name="PublicContainer" style="background-color: rgb(79, 79, 79); flex-direction: column; border-left-width: 5px; border-right-width: 5px; border-top-width: 5px; border-bottom-width: 5px;">
<ui:VisualElement name="HelpBoxContainer" style="flex-grow: 1;" />
<ui:Button text="Settings" display-tooltip-when-elided="true" name="SettingsButton" />
<ui:VisualElement name="PublicContainer1" style="flex-direction: row; flex-wrap: nowrap; height: 28px;">
<ui:Toggle label="Show Packages" name="ShowPackages" style="width: 196px; -unity-text-align: middle-left;" />

View File

@ -4,10 +4,16 @@ namespace YooAsset.Editor
public struct FilterRuleData
{
public string AssetPath;
public string CollectPath;
public string GroupName;
public string UserData;
public FilterRuleData(string assetPath)
public FilterRuleData(string assetPath, string collectPath, string groupName, string userData)
{
AssetPath = assetPath;
CollectPath = collectPath;
GroupName = groupName;
UserData = userData;
}
}

View File

@ -8,13 +8,6 @@ namespace YooAsset.Editor
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, string userData)
{
AssetPath = assetPath;
@ -41,7 +34,7 @@ namespace YooAsset.Editor
public string GetMainBundleName(string packageName, bool uniqueBundleName)
{
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').Replace(" ", "_").ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_{bundleName}.{_bundleExtension}";
else
@ -59,7 +52,7 @@ namespace YooAsset.Editor
return string.Empty;
string fullName;
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').ToLower();
string bundleName = EditorTools.GetRegularPath(_bundleName).Replace('/', '_').Replace('.', '_').Replace(" ", "_").ToLower();
if (uniqueBundleName)
fullName = $"{packageName}_share_{bundleName}.{_bundleExtension}";
else

View File

@ -2,6 +2,15 @@
namespace YooAsset.Editor
{
[DisplayName("定位地址: 禁用")]
public class AddressDisable : IAddressRule
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return string.Empty;
}
}
[DisplayName("定位地址: 文件名")]
public class AddressByFileName : IAddressRule
{
@ -16,7 +25,7 @@ namespace YooAsset.Editor
{
string IAddressRule.GetAssetAddress(AddressRuleData data)
{
return data.AssetPath;
throw new System.Exception("可寻址模式下已经默认支持通过资源路径加载!");
}
}

View File

@ -349,11 +349,25 @@ namespace YooAsset.Editor
private void FillIncludeListView(ReportBundleInfo bundleInfo)
{
List<ReportAssetInfo> containsList = new List<ReportAssetInfo>();
HashSet<string> mainAssetDic = new HashSet<string>();
foreach (var assetInfo in _buildReport.AssetInfos)
{
if (assetInfo.MainBundleName == bundleInfo.BundleName)
{
mainAssetDic.Add(assetInfo.AssetPath);
containsList.Add(assetInfo);
}
}
foreach (string assetPath in bundleInfo.AllBuiltinAssets)
{
if (mainAssetDic.Contains(assetPath) == false)
{
var assetInfo = new ReportAssetInfo();
assetInfo.AssetPath = assetPath;
assetInfo.AssetGUID = "--";
containsList.Add(assetInfo);
}
}
_includeListView.Clear();
_includeListView.ClearSelection();
@ -376,6 +390,16 @@ namespace YooAsset.Editor
element.Add(label);
}
{
var label = new Label();
label.name = "Label3";
label.style.unityTextAlign = TextAnchor.MiddleLeft;
label.style.marginLeft = 3f;
//label.style.flexGrow = 1f;
label.style.width = 100;
element.Add(label);
}
{
var label = new Label();
label.name = "Label2";
@ -397,6 +421,10 @@ namespace YooAsset.Editor
var label1 = element.Q<Label>("Label1");
label1.text = assetInfo.AssetPath;
// Asset Source
var label3 = element.Q<Label>("Label3");
label3.text = assetInfo.AssetGUID != "--" ? "Main Asset" : "Builtin Asset";
// GUID
var label2 = element.Q<Label>("Label2");
label2.text = assetInfo.AssetGUID;

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: a0319abb8eae03b4b88e8f900fe2276c
guid: 8875000dff445624da4d6a2d6ef2f446
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -12,6 +12,7 @@
<ui:VisualElement name="BottomGroup" style="height: 200px; border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-width: 1px; border-left-color: rgb(0, 0, 0); border-right-color: rgb(0, 0, 0); border-top-color: rgb(0, 0, 0); border-bottom-color: rgb(0, 0, 0); margin-left: 0; margin-right: 0; margin-top: 1px; margin-bottom: 1px; display: flex;">
<uie:Toolbar name="BottomBar" style="height: 25px; margin-left: 1px; margin-right: 1px;">
<uie:ToolbarButton text="Include Assets" display-tooltip-when-elided="true" name="BottomBar1" style="width: 280px; -unity-text-align: middle-left; flex-grow: 1;" />
<uie:ToolbarButton text="Asset Source" display-tooltip-when-elided="true" name="BottomBar3" style="width: 100px; -unity-text-align: middle-left;" />
<uie:ToolbarButton text="GUID" display-tooltip-when-elided="true" name="BottomBar2" style="width: 280px; -unity-text-align: middle-left;" />
</uie:Toolbar>
<ui:ListView focusable="true" name="BottomListView" item-height="18" virtualization-method="DynamicHeight" style="flex-grow: 1;" />

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 56d6dbe0d65ce334a8996beb19612989
guid: cf2a9340bb457594d9bc1f80b84a89f6
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}

View File

@ -153,7 +153,7 @@ namespace YooAsset.Editor
guids = AssetDatabase.FindAssets($"t:{searchType}", searchInFolders);
// 注意AssetDatabase.FindAssets()可能会获取到重复的资源
List<string> result = new List<string>();
HashSet<string> result = new HashSet<string>();
for (int i = 0; i < guids.Length; i++)
{
string guid = guids[i];

View File

@ -30,17 +30,22 @@ namespace YooAsset.Editor
public class ShaderVariantInfo
{
/// <summary>
/// Shader asset path in editor.
/// 着色器资源路径.
/// </summary>
public string AssetPath;
/// <summary>
/// Shader name.
/// 着色器名称
/// </summary>
public string ShaderName;
/// <summary>
/// Shader variants elements list.
/// 着色器变种总数
/// </summary>
public int ShaderVariantCount = 0;
/// <summary>
/// 着色器变种列表
/// </summary>
public List<ShaderVariantElement> ShaderVariantElements = new List<ShaderVariantElement>(1000);
}
@ -71,6 +76,7 @@ namespace YooAsset.Editor
element.PassType = passType;
element.Keywords = keywords;
info.ShaderVariantElements.Add(element);
info.ShaderVariantCount++;
}
private ShaderVariantInfo GetOrCreateShaderVariantInfo(string assetPath, string shaderName)
{

View File

@ -72,9 +72,14 @@ namespace YooAsset
_isUnloadSafe = false;
for (int i = 0; i < _providerList.Count; i++)
{
var provider = _providerList[i];
if (provider.IsDone)
continue;
provider.Update();
if (IsBusy)
break;
_providerList[i].Update();
}
_isUnloadSafe = true;
}
@ -128,11 +133,13 @@ namespace YooAsset
#else
foreach (var provider in _providerList)
{
provider.DestroySafely();
provider.WaitForAsyncComplete();
provider.Destroy();
}
foreach (var loader in _loaderList)
{
loader.DestroySafely();
loader.WaitForAsyncComplete();
loader.Destroy();
}
_providerList.Clear();
@ -197,7 +204,7 @@ namespace YooAsset
return completedProvider.CreateHandle<AssetOperationHandle>();
}
string providerGUID = assetInfo.GUID;
string providerGUID = nameof(LoadAssetAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
@ -225,7 +232,7 @@ namespace YooAsset
return completedProvider.CreateHandle<SubAssetsOperationHandle>();
}
string providerGUID = assetInfo.GUID;
string providerGUID = nameof(LoadSubAssetsAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
@ -253,7 +260,7 @@ namespace YooAsset
return completedProvider.CreateHandle<AllAssetsOperationHandle>();
}
string providerGUID = assetInfo.GUID;
string providerGUID = nameof(LoadAllAssetsAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
@ -281,7 +288,7 @@ namespace YooAsset
return completedProvider.CreateHandle<RawFileOperationHandle>();
}
string providerGUID = assetInfo.GUID;
string providerGUID = nameof(LoadRawFileAsync) + assetInfo.GUID;
ProviderBase provider = TryGetProvider(providerGUID);
if (provider == null)
{
@ -416,7 +423,7 @@ namespace YooAsset
return null;
}
#region 调试信息
#region 调试信息
internal List<DebugProviderInfo> GetDebugReportInfos()
{
List<DebugProviderInfo> result = new List<DebugProviderInfo>(_providerList.Count);
@ -444,6 +451,6 @@ namespace YooAsset
}
return result;
}
#endregion
#endregion
}
}

View File

@ -44,12 +44,16 @@ namespace YooAsset
{
if (IsValidWithWarning == false)
return EOperationStatus.None;
if (Provider.Status == ProviderBase.EStatus.Failed)
return EOperationStatus.Failed;
else if (Provider.Status == ProviderBase.EStatus.Succeed)
return EOperationStatus.Succeed;
else
var status = Provider.Status;
if (status == ProviderBase.EStatus.None)
return EOperationStatus.None;
else if (status == ProviderBase.EStatus.Succeed)
return EOperationStatus.Succeed;
else if (status == ProviderBase.EStatus.Failed)
return EOperationStatus.Failed;
else
return EOperationStatus.Processing;
}
}

View File

@ -15,7 +15,8 @@ namespace YooAsset
CheckDownload,
Unpack,
CheckUnpack,
LoadFile,
LoadBundleFile,
LoadDeliveryFile,
CheckLoadFile,
Done,
}
@ -59,19 +60,24 @@ namespace YooAsset
}
else
{
_steps = ESteps.LoadFile;
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
}
#else
_steps = ESteps.LoadFile;
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.StreamingFilePath;
#endif
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
_steps = ESteps.LoadFile;
_steps = ESteps.LoadBundleFile;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery)
{
_steps = ESteps.LoadDeliveryFile;
FileLoadPath = MainBundleInfo.DeliveryFilePath;
}
else
{
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());
@ -103,7 +109,7 @@ namespace YooAsset
}
else
{
_steps = ESteps.LoadFile;
_steps = ESteps.LoadBundleFile;
return; //下载完毕等待一帧再去加载!
}
}
@ -134,12 +140,12 @@ namespace YooAsset
}
else
{
_steps = ESteps.LoadFile;
_steps = ESteps.LoadBundleFile;
}
}
// 5. 加载AssetBundle
if (_steps == ESteps.LoadFile)
if (_steps == ESteps.LoadBundleFile)
{
#if UNITY_EDITOR
// 注意Unity2017.4编辑器模式下如果AssetBundle文件不存在会导致编辑器崩溃这里做了预判。
@ -214,7 +220,35 @@ namespace YooAsset
_steps = ESteps.CheckLoadFile;
}
// 6. 检测AssetBundle加载结果
// 6. 加载AssetBundle
if (_steps == ESteps.LoadDeliveryFile)
{
// 设置下载进度
DownloadProgress = 1f;
DownloadedBytes = (ulong)MainBundleInfo.Bundle.FileSize;
// Load assetBundle file
var loadMethod = (EBundleLoadMethod)MainBundleInfo.Bundle.LoadMethod;
if (loadMethod == EBundleLoadMethod.Normal)
{
ulong offset = MainBundleInfo.DeliveryFileOffset;
if (_isWaitForAsyncComplete)
CacheBundle = AssetBundle.LoadFromFile(FileLoadPath, 0, offset);
else
_createRequest = AssetBundle.LoadFromFileAsync(FileLoadPath, 0, offset);
}
else
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Delivery file not support encryption : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
return;
}
_steps = ESteps.CheckLoadFile;
}
// 7. 检测AssetBundle加载结果
if (_steps == ESteps.CheckLoadFile)
{
if (_createRequest != null)
@ -236,22 +270,47 @@ namespace YooAsset
// Check error
if (CacheBundle == null)
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Failed to load assetBundle : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
// 注意当缓存文件的校验等级为Low的时候并不能保证缓存文件的完整性。
// 在AssetBundle文件加载失败的情况下我们需要重新验证文件的完整性
if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromCache)
{
var result = CacheSystem.VerifyingRecordFile(MainBundleInfo.Bundle.PackageName, MainBundleInfo.Bundle.CacheGUID);
if (result != EVerifyResult.Succeed)
if (result == EVerifyResult.Succeed)
{
YooLogger.Error($"Found possibly corrupt file ! {MainBundleInfo.Bundle.CacheGUID} Verify result : {result}");
// 说明:在安卓移动平台,华为和三星真机上有极小概率加载资源包失败。
// 大多数情况在首次安装下载资源到沙盒内,游戏过程中切换到后台再回到游戏内有很大概率触发!
byte[] fileData = FileUtility.ReadAllBytes(FileLoadPath);
if (fileData != null && fileData.Length > 0)
CacheBundle = AssetBundle.LoadFromMemory(fileData);
if (CacheBundle == null)
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Failed to load assetBundle from memory : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
}
else
{
_steps = ESteps.Done;
Status = EStatus.Succeed;
}
}
else
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Found possibly corrupt file ! {MainBundleInfo.Bundle.CacheGUID} Verify result : {result}";
YooLogger.Error(LastError);
CacheSystem.DiscardFile(MainBundleInfo.Bundle.PackageName, MainBundleInfo.Bundle.CacheGUID);
}
}
else
{
_steps = ESteps.Done;
Status = EStatus.Failed;
LastError = $"Failed to load assetBundle : {MainBundleInfo.Bundle.BundleName}";
YooLogger.Error(LastError);
}
}
else
{

View File

@ -95,9 +95,6 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EStatus.Succeed;
}
// 注意:释放下载句柄
_downloader.DisposeHandler();
}
}

View File

@ -144,15 +144,6 @@ namespace YooAsset
}
}
/// <summary>
/// 销毁资源包(安全模式)
/// </summary>
public void DestroySafely()
{
WaitForAsyncComplete();
Destroy();
}
/// <summary>
/// 轮询更新

View File

@ -54,6 +54,11 @@ namespace YooAsset
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.Bundle.CachedDataFilePath;
}
else if (MainBundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromDelivery)
{
_steps = ESteps.CheckFile;
FileLoadPath = MainBundleInfo.DeliveryFilePath;
}
else
{
throw new System.NotImplementedException(MainBundleInfo.LoadMode.ToString());

View File

@ -140,22 +140,6 @@ namespace YooAsset
}
}
/// <summary>
/// 销毁资源对象(安全模式)
/// </summary>
public void DestroySafely()
{
if (Status == EStatus.Loading || Status == EStatus.Checking)
{
WaitForAsyncComplete();
Destroy();
}
else
{
Destroy();
}
}
/// <summary>
/// 是否可以销毁
/// </summary>

View File

@ -90,6 +90,15 @@ namespace YooAsset
}
}
/// <summary>
/// 获取记录对象
/// </summary>
public static PackageCache.RecordWrapper TryGetWrapper(string packageName, string cacheGUID)
{
var cache = GetOrCreateCache(packageName);
return cache.TryGetWrapper(cacheGUID);
}
/// <summary>
/// 验证缓存文件(子线程内操作)
/// </summary>
@ -165,9 +174,9 @@ namespace YooAsset
/// <summary>
/// 获取所有的缓存文件
/// </summary>
public static List<string> GetAllCacheGUIDs(ResourcePackage package)
public static List<string> GetAllCacheGUIDs(string packageName)
{
var cache = GetOrCreateCache(package.PackageName);
var cache = GetOrCreateCache(packageName);
return cache.GetAllKeys();
}

View File

@ -37,7 +37,7 @@ namespace YooAsset
if (_steps == ESteps.GetAllCacheFiles)
{
_allCacheGUIDs = CacheSystem.GetAllCacheGUIDs(_package);
_allCacheGUIDs = CacheSystem.GetAllCacheGUIDs(_package.PackageName);
_fileTotalCount = _allCacheGUIDs.Count;
YooLogger.Log($"Found all cache file count : {_fileTotalCount}");
_steps = ESteps.ClearAllCacheFiles;

View File

@ -0,0 +1,85 @@
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
public class GetAllCacheFileInfosOperation : AsyncOperationBase
{
public class CacheInfo
{
public string FishHash { private set; get; }
public string FilePath { private set; get; }
public string FileCRC { private set; get; }
public long FileSize { private set; get; }
public CacheInfo(string fishHash, string filePath, string fileCRC, long fileSize)
{
FishHash = fishHash;
FilePath = filePath;
FileCRC = fileCRC;
FileSize = fileSize;
}
}
private enum ESteps
{
None,
GetCacheFileInfos,
Done,
}
private readonly string _packageName;
private ESteps _steps = ESteps.None;
private List<CacheInfo> _cacheFileInfos;
/// <summary>
/// 搜索结果
/// </summary>
public List<CacheInfo> Result
{
get { return _cacheFileInfos; }
}
internal GetAllCacheFileInfosOperation(string packageName)
{
_packageName = packageName;
}
internal override void Start()
{
_steps = ESteps.GetCacheFileInfos;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.GetCacheFileInfos)
{
var allCachedGUIDs = CacheSystem.GetAllCacheGUIDs(_packageName);
_cacheFileInfos = new List<CacheInfo>(allCachedGUIDs.Count);
for (int i = 0; i < allCachedGUIDs.Count; i++)
{
var cachedGUID = allCachedGUIDs[i];
var wrapper = CacheSystem.TryGetWrapper(_packageName, cachedGUID);
if (wrapper != null)
{
string directoryName = Path.GetDirectoryName(wrapper.DataFilePath);
var directoryInfo = new DirectoryInfo(directoryName);
if (directoryInfo.Exists)
{
string fishHash = directoryInfo.Name;
var cacheFileInfo = new CacheInfo(fishHash, wrapper.DataFilePath, wrapper.DataFileCRC, wrapper.DataFileSize);
_cacheFileInfos.Add(cacheFileInfo);
}
}
}
// 注意:总是返回成功
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
}
}
}

View File

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

View File

@ -46,7 +46,12 @@ namespace YooAsset
}
private static string CreateDefaultBuildinRoot()
{
return PathUtility.Combine(UnityEngine.Application.streamingAssetsPath, YooAssetSettings.DefaultYooFolderName);
string path = PathUtility.Combine(UnityEngine.Application.streamingAssetsPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#if UNITY_OPENHARMONY
return $"file://{path}";
#else
return path;
#endif
}
private static string CreateDefaultSandboxRoot()
{
@ -54,11 +59,11 @@ namespace YooAsset
// 注意:为了方便调试查看,编辑器下把存储目录放到项目里。
string projectPath = Path.GetDirectoryName(UnityEngine.Application.dataPath);
projectPath = PathUtility.RegularPath(projectPath);
return PathUtility.Combine(projectPath, YooAssetSettings.DefaultYooFolderName);
return PathUtility.Combine(projectPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#elif UNITY_STANDALONE
return PathUtility.Combine(UnityEngine.Application.dataPath, YooAssetSettings.DefaultYooFolderName);
return PathUtility.Combine(UnityEngine.Application.dataPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#else
return PathUtility.Combine(UnityEngine.Application.persistentDataPath, YooAssetSettings.DefaultYooFolderName);
return PathUtility.Combine(UnityEngine.Application.persistentDataPath, YooAssetSettingsData.Setting.DefaultYooFolderName);
#endif
}
@ -128,6 +133,7 @@ namespace YooAsset
/// </summary>
public void SaveSandboxPackageVersionFile(string version)
{
YooLogger.Log($"Save package version : {version}");
string filePath = GetSandboxPackageVersionFilePath();
FileUtility.WriteAllText(filePath, version);
}

View File

@ -37,13 +37,22 @@ namespace YooAsset
{
#if UNITY_EDITOR
return StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL
return path;
#elif UNITY_IPHONE
return StringUtility.Format("file://{0}", path);
#elif UNITY_ANDROID
if (path.StartsWith("jar:file://"))
return path;
else
return StringUtility.Format("jar:file://{0}", path);
#elif UNITY_STANDALONE_OSX
return new System.Uri(path).ToString();
#elif UNITY_STANDALONE
return StringUtility.Format("file:///{0}", path);
#elif UNITY_WEBGL
#elif UNITY_OPENHARMONY
return path;
#else
return path;
#endif
}

View File

@ -28,14 +28,13 @@ namespace YooAsset
public void DeleteFiles()
{
if (File.Exists(DataFilePath))
try
{
File.Delete(DataFilePath);
Directory.Delete(FileRootPath, true);
}
if (File.Exists(InfoFilePath))
catch (System.Exception e)
{
File.Delete(InfoFilePath);
YooLogger.Warning($"Failed delete cache bundle folder : {e}");
}
}
}

View File

@ -51,6 +51,9 @@ namespace YooAsset
// 准备下载
if (_steps == ESteps.PrepareDownload)
{
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
_downloadProgress = 0f;
_downloadedBytes = 0;
@ -59,14 +62,16 @@ namespace YooAsset
_isAbort = false;
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
// 重置计时器
if(_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f;
// 删除临时文件
if (File.Exists(_tempFilePath))
File.Delete(_tempFilePath);
// 获取请求地址
_requestURL = GetRequestURL();
_steps = ESteps.CreateDownloader;
}
@ -197,7 +202,6 @@ namespace YooAsset
_failedTryAgain--;
_steps = ESteps.PrepareDownload;
ReportWarning();
YooLogger.Warning($"Try again download : {_requestURL}");
}
}
}

View File

@ -91,6 +91,9 @@ namespace YooAsset
// 创建下载器
if (_steps == ESteps.PrepareDownload)
{
// 获取请求地址
_requestURL = GetRequestURL();
// 重置变量
_downloadProgress = 0f;
_downloadedBytes = 0;
@ -99,11 +102,13 @@ namespace YooAsset
_isAbort = false;
_latestDownloadBytes = 0;
_latestDownloadRealtime = Time.realtimeSinceStartup;
_tryAgainTimer = 0f;
_fileOriginLength = 0;
// 获取请求地址
_requestURL = GetRequestURL();
// 重置计时器
if (_tryAgainTimer > 0f)
YooLogger.Warning($"Try again download : {_requestURL}");
_tryAgainTimer = 0f;
_steps = ESteps.CreateDownloader;
}
@ -257,7 +262,6 @@ namespace YooAsset
_failedTryAgain--;
_steps = ESteps.PrepareDownload;
ReportWarning();
YooLogger.Warning($"Try again download : {_requestURL}");
}
}
}

View File

@ -22,10 +22,10 @@ namespace YooAsset
Done,
}
private bool _keepDownloadHandleLife = false;
private DownloadHandlerAssetBundle _downloadhandler;
private ESteps _steps = ESteps.None;
private bool _getAssetBundle = false;
private AssetBundle _cacheAssetBundle;
public WebDownloader(BundleInfo bundleInfo, int failedTryAgain, int timeout) : base(bundleInfo, failedTryAgain, timeout)
{
@ -34,7 +34,10 @@ namespace YooAsset
{
if (_steps == ESteps.None)
{
_keepDownloadHandleLife = (bool)param[0];
if (param.Length > 0)
{
_getAssetBundle = (bool)param[0];
}
_steps = ESteps.PrepareDownload;
}
}
@ -72,14 +75,18 @@ namespace YooAsset
{
uint crc = _bundleInfo.Bundle.UnityCRC;
_downloadhandler = new DownloadHandlerAssetBundle(_requestURL, crc);
#if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false;
#endif
}
else
{
uint crc = _bundleInfo.Bundle.UnityCRC;
var hash = Hash128.Parse(_bundleInfo.Bundle.FileHash);
_downloadhandler = new DownloadHandlerAssetBundle(_requestURL, hash, crc);
#if UNITY_2020_3_OR_NEWER
_downloadhandler.autoLoadAssetBundle = false;
#endif
}
_webRequest.downloadHandler = _downloadhandler;
@ -131,11 +138,18 @@ namespace YooAsset
_lastCode = 0;
}
if (_getAssetBundle)
{
_cacheAssetBundle = _downloadhandler.assetBundle;
if (_cacheAssetBundle == null)
{
_lastError = "assetBundle is null";
_steps = ESteps.TryAgain;
}
}
// 最终释放请求
DisposeRequest();
if (_keepDownloadHandleLife == false)
DisposeHandler();
}
// 重新尝试下载
@ -144,7 +158,6 @@ namespace YooAsset
if (_failedTryAgain <= 0)
{
DisposeRequest();
DisposeHandler();
ReportError();
_status = EStatus.Failed;
_steps = ESteps.Done;
@ -171,7 +184,6 @@ namespace YooAsset
_lastCode = 0;
DisposeRequest();
DisposeHandler();
}
}
private void DisposeRequest()
@ -181,6 +193,11 @@ namespace YooAsset
_webRequest.Dispose();
_webRequest = null;
}
if (_downloadhandler != null)
{
_downloadhandler.Dispose();
_downloadhandler = null;
}
}
/// <summary>
@ -188,22 +205,7 @@ namespace YooAsset
/// </summary>
public AssetBundle GetAssetBundle()
{
if (_downloadhandler != null)
return _downloadhandler.assetBundle;
return null;
}
/// <summary>
/// 释放下载句柄
/// </summary>
public void DisposeHandler()
{
if (_downloadhandler != null)
{
_downloadhandler.Dispose();
_downloadhandler = null;
}
return _cacheAssetBundle;
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace YooAsset
{
public class RequestHelper
{
/// <summary>
/// 记录网络请求失败事件的次数
/// </summary>
private static readonly Dictionary<string, int> _requestFailedRecorder = new Dictionary<string, int>(1000);
/// <summary>
/// 记录请求失败事件
/// </summary>
public static void RecordRequestFailed(string packageName, string eventName)
{
string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0);
_requestFailedRecorder[key]++;
}
/// <summary>
/// 获取请求失败的次数
/// </summary>
public static int GetRequestFailedCount(string packageName, string eventName)
{
string key = $"{packageName}_{eventName}";
if (_requestFailedRecorder.ContainsKey(key) == false)
_requestFailedRecorder.Add(key, 0);
return _requestFailedRecorder[key];
}
}
}

View File

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

View File

@ -88,7 +88,12 @@ namespace YooAsset
/// <summary>
/// 内置资源查询服务接口
/// </summary>
public IQueryServices QueryServices = null;
public IBuildinQueryServices BuildinQueryServices = null;
/// <summary>
/// 分发资源查询服务接口
/// </summary>
public IDeliveryQueryServices DeliveryQueryServices = null;
/// <summary>
/// 远端资源地址查询服务类
@ -104,7 +109,7 @@ namespace YooAsset
/// <summary>
/// 内置资源查询服务接口
/// </summary>
public IQueryServices QueryServices = null;
public IBuildinQueryServices BuildinQueryServices = null;
/// <summary>
/// 远端资源地址查询服务类

View File

@ -73,13 +73,18 @@ namespace YooAsset
internal abstract void Start();
internal abstract void Update();
internal void Finish()
internal void SetFinish()
{
Progress = 1f;
_callback?.Invoke(this);
_callback?.Invoke(this); //注意如果完成回调内发生异常会导致Task无限期等待
if (_taskCompletionSource != null)
_taskCompletionSource.TrySetResult(null);
}
internal void SetStart()
{
Status = EOperationStatus.Processing;
}
/// <summary>
/// 清空完成回调

View File

@ -4,6 +4,7 @@ namespace YooAsset
public enum EOperationStatus
{
None,
Processing,
Succeed,
Failed
}

View File

@ -7,8 +7,7 @@ namespace YooAsset
internal class OperationSystem
{
private static readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _addList = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _removeList = new List<AsyncOperationBase>(100);
private static readonly List<AsyncOperationBase> _newList = new List<AsyncOperationBase>(100);
// 计时器相关
private static Stopwatch _watch;
@ -47,39 +46,26 @@ namespace YooAsset
_frameTime = _watch.ElapsedMilliseconds;
// 添加新的异步操作
if (_addList.Count > 0)
if (_newList.Count > 0)
{
for (int i = 0; i < _addList.Count; i++)
{
var operation = _addList[i];
_operations.Add(operation);
}
_addList.Clear();
_operations.AddRange(_newList);
_newList.Clear();
}
// 更新所有的异步操作
foreach (var operation in _operations)
for (int i = _operations.Count - 1; i >= 0; i--)
{
if (IsBusy)
break;
var operation = _operations[i];
operation.Update();
if (operation.IsDone)
{
_removeList.Add(operation);
operation.Finish();
_operations.RemoveAt(i);
operation.SetFinish(); //注意:如果业务端发生异常,保证异步操作提前移除。
}
}
// 移除已经完成的异步操作
if (_removeList.Count > 0)
{
foreach (var operation in _removeList)
{
_operations.Remove(operation);
}
_removeList.Clear();
}
}
/// <summary>
@ -88,8 +74,7 @@ namespace YooAsset
public static void DestroyAll()
{
_operations.Clear();
_addList.Clear();
_removeList.Clear();
_newList.Clear();
_watch = null;
_frameTime = 0;
MaxTimeSlice = long.MaxValue;
@ -100,7 +85,8 @@ namespace YooAsset
/// </summary>
public static void StartOperation(AsyncOperationBase operation)
{
_addList.Add(operation);
_newList.Add(operation);
operation.SetStart();
operation.Start();
}
}

View File

@ -28,9 +28,9 @@ namespace YooAsset
return _providerGUID;
if (AssetType == null)
_providerGUID = $"{AssetPath}[null]";
_providerGUID = $"[{AssetPath}][null]";
else
_providerGUID = $"{AssetPath}[{AssetType.Name}]";
_providerGUID = $"[{AssetPath}][{AssetType.Name}]";
return _providerGUID;
}
}

View File

@ -6,6 +6,7 @@ namespace YooAsset
public enum ELoadMode
{
None,
LoadFromDelivery,
LoadFromStreaming,
LoadFromCache,
LoadFromRemote,
@ -25,6 +26,16 @@ namespace YooAsset
/// </summary>
public string RemoteFallbackURL { private set; get; }
/// <summary>
/// 开发者分发的文件地址
/// </summary>
public string DeliveryFilePath { private set; get; }
/// <summary>
/// 开发者分发的文件偏移量
/// </summary>
public ulong DeliveryFileOffset { private set; get; }
/// <summary>
/// 注意:该字段只用于帮助编辑器下的模拟模式。
/// </summary>
@ -40,6 +51,17 @@ namespace YooAsset
LoadMode = loadMode;
RemoteMainURL = mainURL;
RemoteFallbackURL = fallbackURL;
DeliveryFilePath = string.Empty;
DeliveryFileOffset = 0;
}
public BundleInfo(PackageBundle bundle, ELoadMode loadMode, string deliveryFilePath, ulong deliveryFileOffset)
{
Bundle = bundle;
LoadMode = loadMode;
RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty;
DeliveryFilePath = deliveryFilePath;
DeliveryFileOffset = deliveryFileOffset;
}
public BundleInfo(PackageBundle bundle, ELoadMode loadMode)
{
@ -47,6 +69,8 @@ namespace YooAsset
LoadMode = loadMode;
RemoteMainURL = string.Empty;
RemoteFallbackURL = string.Empty;
DeliveryFilePath = string.Empty;
DeliveryFileOffset = 0;
}
/// <summary>

View File

@ -154,10 +154,12 @@ namespace YooAsset
// 填充BundleDic
manifest.BundleDic = new Dictionary<string, PackageBundle>(manifest.BundleList.Count);
manifest.BundleDic2 = new Dictionary<string, PackageBundle>(manifest.BundleList.Count);
foreach (var packageBundle in manifest.BundleList)
{
packageBundle.ParseBundle(manifest.PackageName, manifest.OutputNameStyle);
manifest.BundleDic.Add(packageBundle.BundleName, packageBundle);
manifest.BundleDic2.Add(packageBundle.FileName, packageBundle);
}
// 填充AssetDic
@ -210,7 +212,18 @@ namespace YooAsset
}
/// <summary>
/// 批量转换为解压BundleInfo
/// 转换为导入BundleInfo
/// </summary>
public static BundleInfo ConvertToImportInfo(PackageBundle packageBundle, string filePath)
{
// 注意:我们把本地文件路径指定为远端下载地址
string persistentPath = PersistentTools.ConvertToWWWPath(filePath);
BundleInfo bundleInfo = new BundleInfo(packageBundle, BundleInfo.ELoadMode.None, persistentPath, persistentPath);
return bundleInfo;
}
/// <summary>
/// 批量转换解压为BundleInfo
/// </summary>
public static List<BundleInfo> ConvertToUnpackInfos(List<PackageBundle> unpackList)
{

View File

@ -91,14 +91,7 @@ namespace YooAsset
_failedTryAgain = failedTryAgain;
_timeout = timeout;
if (downloadList != null)
{
TotalDownloadCount = downloadList.Count;
foreach (var packageBundle in downloadList)
{
TotalDownloadBytes += packageBundle.Bundle.FileSize;
}
}
CalculatDownloaderInfo();
}
internal override void Start()
{
@ -206,6 +199,57 @@ namespace YooAsset
}
}
}
private void CalculatDownloaderInfo()
{
if (_downloadList != null)
{
TotalDownloadBytes = 0;
TotalDownloadCount = _downloadList.Count;
foreach (var packageBundle in _downloadList)
{
TotalDownloadBytes += packageBundle.Bundle.FileSize;
}
}
else
{
TotalDownloadBytes = 0;
TotalDownloadCount = 0;
}
}
/// <summary>
/// 合并其它下载器
/// </summary>
/// <param name="downloader">合并的下载器</param>
public void Combine(DownloaderOperation downloader)
{
if (_steps != ESteps.None)
{
YooLogger.Error("The downloader is running, can not combine with other downloader !");
return;
}
HashSet<string> temper = new HashSet<string>();
foreach (var bundleInfo in _downloadList)
{
if (temper.Contains(bundleInfo.Bundle.CachedDataFilePath) == false)
{
temper.Add(bundleInfo.Bundle.CachedDataFilePath);
}
}
// 合并下载列表
foreach (var bundleInfo in downloader._downloadList)
{
if (temper.Contains(bundleInfo.Bundle.CachedDataFilePath) == false)
{
_downloadList.Add(bundleInfo);
}
}
// 重新统计下载信息
CalculatDownloaderInfo();
}
/// <summary>
/// 开始下载
@ -282,4 +326,21 @@ namespace YooAsset
return operation;
}
}
public sealed class ResourceImporterOperation : DownloaderOperation
{
internal ResourceImporterOperation(List<BundleInfo> downloadList, int downloadingMaxNumber, int failedTryAgain, int timeout)
: base(downloadList, downloadingMaxNumber, failedTryAgain, timeout)
{
}
/// <summary>
/// 创建空的导入器
/// </summary>
internal static ResourceImporterOperation CreateEmptyImporter(int upackingMaxNumber, int failedTryAgain, int timeout)
{
List<BundleInfo> downloadList = new List<BundleInfo>();
var operation = new ResourceImporterOperation(downloadList, upackingMaxNumber, failedTryAgain, int.MaxValue);
return operation;
}
}
}

View File

@ -11,6 +11,11 @@ namespace YooAsset
public abstract class InitializationOperation : AsyncOperationBase
{
public string PackageVersion { protected set; get; }
/// <summary>
/// 本地记录的资源包裹的版本
/// </summary>
public string RecordVersion { protected set; get; }
}
/// <summary>
@ -242,6 +247,7 @@ namespace YooAsset
if (_queryCachePackageVersionOp.Status == EOperationStatus.Succeed)
{
RecordVersion = _queryCachePackageVersionOp.PackageVersion;
_steps = ESteps.TryLoadCacheManifest;
}
else
@ -336,6 +342,7 @@ namespace YooAsset
{
PackageVersion = _loadBuildinManifestOp.Manifest.PackageVersion;
_impl.ActiveManifest = _loadBuildinManifestOp.Manifest;
_impl.FlushManifestVersionFile();
_steps = ESteps.PackageCaching;
}
else

View File

@ -97,7 +97,7 @@ namespace YooAsset
Manifest.AssetDic = new Dictionary<string, PackageAsset>(_packageAssetCount);
if (Manifest.EnableAddressable)
Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount);
Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 3);
else
Manifest.AssetPathMapping1 = new Dictionary<string, string>(_packageAssetCount * 2);
@ -130,15 +130,6 @@ namespace YooAsset
Manifest.AssetDic.Add(assetPath, packageAsset);
// 填充AssetPathMapping1
if (Manifest.EnableAddressable)
{
string location = packageAsset.Address;
if (Manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Address have existed : {location}");
else
Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
}
else
{
string location = packageAsset.AssetPath;
if (Manifest.LocationToLower)
@ -146,20 +137,31 @@ namespace YooAsset
// 添加原生路径的映射
if (Manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"AssetPath have existed : {location}");
throw new System.Exception($"Location have existed : {location}");
else
Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
// 添加无后缀名路径的映射
if (Path.HasExtension(location))
string locationWithoutExtension = Path.ChangeExtension(location, null);
if (!ReferenceEquals(location, locationWithoutExtension))
{
string locationWithoutExtension = PathUtility.RemoveExtension(location);
if (Manifest.AssetPathMapping1.ContainsKey(locationWithoutExtension))
YooLogger.Warning($"AssetPath have existed : {locationWithoutExtension}");
YooLogger.Warning($"Location have existed : {locationWithoutExtension}");
else
Manifest.AssetPathMapping1.Add(locationWithoutExtension, packageAsset.AssetPath);
}
}
if (Manifest.EnableAddressable)
{
string location = packageAsset.Address;
if (string.IsNullOrEmpty(location) == false)
{
if (Manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Location have existed : {location}");
else
Manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
}
}
// 填充AssetPathMapping2
if (Manifest.IncludeAssetGUID)
@ -187,6 +189,8 @@ namespace YooAsset
_packageBundleCount = _buffer.ReadInt32();
Manifest.BundleList = new List<PackageBundle>(_packageBundleCount);
Manifest.BundleDic = new Dictionary<string, PackageBundle>(_packageBundleCount);
Manifest.BundleDic2 = new Dictionary<string, PackageBundle>(_packageBundleCount);
Manifest.BundleDic3 = new Dictionary<string, PackageBundle>(_packageBundleCount);
_progressTotalValue = _packageBundleCount;
_steps = ESteps.DeserializeBundleList;
}
@ -208,6 +212,11 @@ namespace YooAsset
packageBundle.ParseBundle(Manifest.PackageName, Manifest.OutputNameStyle);
Manifest.BundleDic.Add(packageBundle.BundleName, packageBundle);
Manifest.BundleDic2.Add(packageBundle.FileName, packageBundle);
// 注意原始文件可能存在相同的CacheGUID
if (Manifest.BundleDic3.ContainsKey(packageBundle.CacheGUID) == false)
Manifest.BundleDic3.Add(packageBundle.CacheGUID, packageBundle);
_packageBundleCount--;
Progress = 1f - _packageBundleCount / _progressTotalValue;

View File

@ -11,7 +11,6 @@ namespace YooAsset
Done,
}
private static int RequestCount = 0;
private readonly IRemoteServices _remoteServices;
private readonly string _packageName;
private readonly string _packageVersion;
@ -19,6 +18,7 @@ namespace YooAsset
private UnityWebFileRequester _downloader1;
private UnityWebFileRequester _downloader2;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
internal DownloadManifestOperation(IRemoteServices remoteServices, string packageName, string packageVersion, int timeout)
{
@ -29,7 +29,7 @@ namespace YooAsset
}
internal override void Start()
{
RequestCount++;
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(DownloadManifestOperation));
_steps = ESteps.DownloadPackageHashFile;
}
internal override void Update()
@ -58,6 +58,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader1.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(DownloadManifestOperation));
}
else
{
@ -74,7 +75,7 @@ namespace YooAsset
string savePath = PersistentTools.GetPersistent(_packageName).GetSandboxPackageManifestFilePath(_packageVersion);
string fileName = YooAssetSettingsData.GetManifestBinaryFileName(_packageName, _packageVersion);
string webURL = GetDownloadRequestURL(fileName);
YooLogger.Log($"Beginning to download manifest file : {webURL}");
YooLogger.Log($"Beginning to download package manifest file : {webURL}");
_downloader2 = new UnityWebFileRequester();
_downloader2.SendRequest(webURL, savePath, _timeout);
}
@ -88,6 +89,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader2.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(DownloadManifestOperation));
}
else
{
@ -102,10 +104,10 @@ namespace YooAsset
private string GetDownloadRequestURL(string fileName)
{
// 轮流返回请求地址
if (RequestCount % 2 == 0)
return _remoteServices.GetRemoteFallbackURL(fileName);
else
if (_requestCount % 2 == 0)
return _remoteServices.GetRemoteMainURL(fileName);
else
return _remoteServices.GetRemoteFallbackURL(fileName);
}
}
}

View File

@ -13,7 +13,6 @@ namespace YooAsset
Done,
}
private static int RequestCount = 0;
private readonly IRemoteServices _remoteServices;
private readonly string _packageName;
private readonly string _packageVersion;
@ -23,6 +22,7 @@ namespace YooAsset
private DeserializeManifestOperation _deserializer;
private byte[] _fileData;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
/// <summary>
/// 加载的清单实例
@ -39,7 +39,7 @@ namespace YooAsset
}
internal override void Start()
{
RequestCount++;
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(LoadRemoteManifestOperation));
_steps = ESteps.DownloadPackageHashFile;
}
internal override void Update()
@ -90,6 +90,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(LoadRemoteManifestOperation));
}
else
{
@ -141,10 +142,10 @@ namespace YooAsset
private string GetDownloadRequestURL(string fileName)
{
// 轮流返回请求地址
if (RequestCount % 2 == 0)
return _remoteServices.GetRemoteFallbackURL(fileName);
else
if (_requestCount % 2 == 0)
return _remoteServices.GetRemoteMainURL(fileName);
else
return _remoteServices.GetRemoteFallbackURL(fileName);
}
}
}

View File

@ -10,13 +10,13 @@ namespace YooAsset
Done,
}
private static int RequestCount = 0;
private readonly IRemoteServices _remoteServices;
private readonly string _packageName;
private readonly string _packageVersion;
private readonly int _timeout;
private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
/// <summary>
/// 包裹哈希值
@ -33,7 +33,7 @@ namespace YooAsset
}
internal override void Start()
{
RequestCount++;
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageHashOperation));
_steps = ESteps.DownloadPackageHash;
}
internal override void Update()
@ -62,6 +62,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageHashOperation));
}
else
{
@ -88,10 +89,10 @@ namespace YooAsset
string url;
// 轮流返回请求地址
if (RequestCount % 2 == 0)
url = _remoteServices.GetRemoteFallbackURL(fileName);
else
if (_requestCount % 2 == 0)
url = _remoteServices.GetRemoteMainURL(fileName);
else
url = _remoteServices.GetRemoteFallbackURL(fileName);
return url;
}

View File

@ -10,13 +10,13 @@ namespace YooAsset
Done,
}
private static int RequestCount = 0;
private readonly IRemoteServices _remoteServices;
private readonly string _packageName;
private readonly bool _appendTimeTicks;
private readonly int _timeout;
private UnityWebDataRequester _downloader;
private ESteps _steps = ESteps.None;
private int _requestCount = 0;
/// <summary>
/// 包裹版本
@ -33,7 +33,7 @@ namespace YooAsset
}
internal override void Start()
{
RequestCount++;
_requestCount = RequestHelper.GetRequestFailedCount(_packageName, nameof(QueryRemotePackageVersionOperation));
_steps = ESteps.DownloadPackageVersion;
}
internal override void Update()
@ -62,6 +62,7 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = _downloader.GetError();
RequestHelper.RecordRequestFailed(_packageName, nameof(QueryRemotePackageVersionOperation));
}
else
{
@ -88,10 +89,10 @@ namespace YooAsset
string url;
// 轮流返回请求地址
if (RequestCount % 2 == 0)
url = _remoteServices.GetRemoteFallbackURL(fileName);
else
if (_requestCount % 2 == 0)
url = _remoteServices.GetRemoteMainURL(fileName);
else
url = _remoteServices.GetRemoteFallbackURL(fileName);
// 在URL末尾添加时间戳
if (_appendTimeTicks)

View File

@ -58,6 +58,7 @@ namespace YooAsset
private enum ESteps
{
None,
CheckParams,
CheckActiveManifest,
TryLoadCacheManifest,
DownloadManifest,
@ -87,13 +88,34 @@ namespace YooAsset
}
internal override void Start()
{
_steps = ESteps.CheckActiveManifest;
_steps = ESteps.CheckParams;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CheckParams)
{
if (string.IsNullOrEmpty(_packageName))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Package name is null or empty.";
return;
}
if (string.IsNullOrEmpty(_packageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Package version is null or empty.";
return;
}
_steps = ESteps.CheckActiveManifest;
}
if (_steps == ESteps.CheckActiveManifest)
{
// 检测当前激活的清单对象
@ -198,6 +220,7 @@ namespace YooAsset
private enum ESteps
{
None,
CheckParams,
CheckActiveManifest,
LoadRemoteManifest,
Done,
@ -220,13 +243,34 @@ namespace YooAsset
}
internal override void Start()
{
_steps = ESteps.CheckActiveManifest;
_steps = ESteps.CheckParams;
}
internal override void Update()
{
if (_steps == ESteps.None || _steps == ESteps.Done)
return;
if (_steps == ESteps.CheckParams)
{
if (string.IsNullOrEmpty(_packageName))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Package name is null or empty.";
return;
}
if (string.IsNullOrEmpty(_packageVersion))
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = "Package version is null or empty.";
return;
}
_steps = ESteps.CheckActiveManifest;
}
if (_steps == ESteps.CheckActiveManifest)
{
// 检测当前激活的清单对象

View File

@ -64,6 +64,18 @@ namespace YooAsset
[NonSerialized]
public Dictionary<string, PackageBundle> BundleDic;
/// <summary>
/// 资源包集合提供FileName获取PackageBundle
/// </summary>
[NonSerialized]
public Dictionary<string, PackageBundle> BundleDic2;
/// <summary>
/// 资源包集合提供CacheGUID获取PackageBundle
/// </summary>
[NonSerialized]
public Dictionary<string, PackageBundle> BundleDic3;
/// <summary>
/// 资源映射集合提供AssetPath获取PackageAsset
/// </summary>
@ -186,17 +198,28 @@ namespace YooAsset
return BundleDic.TryGetValue(bundleName, out result);
}
/// <summary>
/// 尝试获取包裹的资源包
/// </summary>
public bool TryGetPackageBundleByFileName(string fileName, out PackageBundle result)
{
return BundleDic2.TryGetValue(fileName, out result);
}
/// <summary>
/// 尝试获取包裹的资源包
/// </summary>
public bool TryGetPackageBundleByCacheGUID(string cacheGUID, out PackageBundle result)
{
return BundleDic3.TryGetValue(cacheGUID, out result);
}
/// <summary>
/// 是否包含资源文件
/// </summary>
public bool IsIncludeBundleFile(string cacheGUID)
{
foreach (var packageBundle in BundleList)
{
if (packageBundle.CacheGUID == cacheGUID)
return true;
}
return false;
return BundleDic3.ContainsKey(cacheGUID);
}
/// <summary>

View File

@ -74,6 +74,11 @@ namespace YooAsset
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
ResourceImporterOperation IPlayModeServices.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{
return ResourceImporterOperation.CreateEmptyImporter(importerMaxNumber, failedTryAgain, timeout);
}
#endregion
#region IBundleServices接口

View File

@ -10,7 +10,8 @@ namespace YooAsset
// 参数相关
private string _packageName;
private IQueryServices _queryServices;
private IBuildinQueryServices _buildinQueryServices;
private IDeliveryQueryServices _deliveryQueryServices;
private IRemoteServices _remoteServices;
public IRemoteServices RemoteServices
@ -21,10 +22,11 @@ namespace YooAsset
/// <summary>
/// 异步初始化
/// </summary>
public InitializationOperation InitializeAsync(string packageName, IQueryServices queryServices, IRemoteServices remoteServices)
public InitializationOperation InitializeAsync(string packageName, IBuildinQueryServices buildinQueryServices, IDeliveryQueryServices deliveryQueryServices, IRemoteServices remoteServices)
{
_packageName = packageName;
_queryServices = queryServices;
_buildinQueryServices = buildinQueryServices;
_deliveryQueryServices = deliveryQueryServices;
_remoteServices = remoteServices;
var operation = new HostPlayModeInitializationOperation(this, packageName);
@ -51,6 +53,24 @@ namespace YooAsset
return bundleInfo;
}
// 查询相关
private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{
return _buildinQueryServices.QueryStreamingAssets(_packageName, packageBundle.FileName);
}
private bool IsCachedPackageBundle(PackageBundle packageBundle)
{
return CacheSystem.IsCached(packageBundle.PackageName, packageBundle.CacheGUID);
}
private bool IsDeliveryPackageBundle(PackageBundle packageBundle)
{
return _deliveryQueryServices.QueryDeliveryFiles(_packageName, packageBundle.FileName);
}
private DeliveryFileInfo GetDeiveryFileInfo(PackageBundle packageBundle)
{
return _deliveryQueryServices.GetDeliveryFileInfo(_packageName, packageBundle.FileName);
}
#region IPlayModeServices接口
public PackageManifest ActiveManifest
{
@ -71,15 +91,6 @@ namespace YooAsset
}
}
private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{
return _queryServices.QueryStreamingAssets(_packageName, packageBundle.FileName);
}
private bool IsCachedPackageBundle(PackageBundle packageBundle)
{
return CacheSystem.IsCached(packageBundle.PackageName, packageBundle.CacheGUID);
}
UpdatePackageVersionOperation IPlayModeServices.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{
var operation = new HostPlayModeUpdatePackageVersionOperation(this, _packageName, appendTimeTicks, timeout);
@ -110,6 +121,10 @@ namespace YooAsset
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList)
{
// 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle))
continue;
// 忽略缓存文件
if (IsCachedPackageBundle(packageBundle))
continue;
@ -135,6 +150,10 @@ namespace YooAsset
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList)
{
// 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle))
continue;
// 忽略缓存文件
if (IsCachedPackageBundle(packageBundle))
continue;
@ -196,6 +215,10 @@ namespace YooAsset
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in checkList)
{
// 忽略分发文件
if (IsDeliveryPackageBundle(packageBundle))
continue;
// 忽略缓存文件
if (IsCachedPackageBundle(packageBundle))
continue;
@ -261,6 +284,39 @@ namespace YooAsset
return ManifestTools.ConvertToUnpackInfos(downloadList);
}
ResourceImporterOperation IPlayModeServices.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{
List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths);
var operation = new ResourceImporterOperation(importerList, importerMaxNumber, failedTryAgain, timeout);
return operation;
}
private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths)
{
List<BundleInfo> result = new List<BundleInfo>();
foreach (var filePath in filePaths)
{
string fileName = System.IO.Path.GetFileName(filePath);
if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle))
{
// 忽略缓存文件
if (IsCachedPackageBundle(packageBundle))
continue;
// 忽略APP资源
if (IsBuildinPackageBundle(packageBundle))
continue;
var bundleInfo = ManifestTools.ConvertToImportInfo(packageBundle, filePath);
result.Add(bundleInfo);
}
else
{
YooLogger.Warning($"Not found package bundle, importer file path : {filePath}");
}
}
return result;
}
#endregion
#region IBundleServices接口
@ -269,6 +325,14 @@ namespace YooAsset
if (packageBundle == null)
throw new Exception("Should never get here !");
// 查询分发资源
if (IsDeliveryPackageBundle(packageBundle))
{
DeliveryFileInfo deliveryFileInfo = GetDeiveryFileInfo(packageBundle);
BundleInfo bundleInfo = new BundleInfo(packageBundle, BundleInfo.ELoadMode.LoadFromDelivery, deliveryFileInfo.DeliveryFilePath, deliveryFileInfo.DeliveryFileOffset);
return bundleInfo;
}
// 查询沙盒资源
if (IsCachedPackageBundle(packageBundle))
{

View File

@ -18,6 +18,12 @@ namespace YooAsset
return operation;
}
// 查询相关
private bool IsCachedPackageBundle(PackageBundle packageBundle)
{
return CacheSystem.IsCached(packageBundle.PackageName, packageBundle.CacheGUID);
}
#region IPlayModeServices接口
public PackageManifest ActiveManifest
{
@ -34,11 +40,6 @@ namespace YooAsset
{
}
private bool IsCachedPackageBundle(PackageBundle packageBundle)
{
return CacheSystem.IsCached(packageBundle.PackageName, packageBundle.CacheGUID);
}
UpdatePackageVersionOperation IPlayModeServices.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{
var operation = new OfflinePlayModeUpdatePackageVersionOperation();
@ -116,6 +117,35 @@ namespace YooAsset
return ManifestTools.ConvertToUnpackInfos(downloadList);
}
ResourceImporterOperation IPlayModeServices.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{
List<BundleInfo> importerList = GetImporterListByFilePaths(_activeManifest, filePaths);
var operation = new ResourceImporterOperation(importerList, importerMaxNumber, failedTryAgain, timeout);
return operation;
}
private List<BundleInfo> GetImporterListByFilePaths(PackageManifest manifest, string[] filePaths)
{
List<BundleInfo> result = new List<BundleInfo>();
foreach (var filePath in filePaths)
{
string fileName = System.IO.Path.GetFileName(filePath);
if (manifest.TryGetPackageBundleByFileName(fileName, out PackageBundle packageBundle))
{
// 忽略缓存文件
if (IsCachedPackageBundle(packageBundle))
continue;
var bundleInfo = ManifestTools.ConvertToImportInfo(packageBundle, filePath);
result.Add(bundleInfo);
}
else
{
YooLogger.Warning($"Not found package bundle, importer file path : {filePath}");
}
}
return result;
}
#endregion
#region IBundleServices接口

View File

@ -10,7 +10,7 @@ namespace YooAsset
// 参数相关
private string _packageName;
private IQueryServices _queryServices;
private IBuildinQueryServices _buildinQueryServices;
private IRemoteServices _remoteServices;
public IRemoteServices RemoteServices
@ -21,10 +21,10 @@ namespace YooAsset
/// <summary>
/// 异步初始化
/// </summary>
public InitializationOperation InitializeAsync(string packageName, IQueryServices queryServices, IRemoteServices remoteServices)
public InitializationOperation InitializeAsync(string packageName, IBuildinQueryServices buildinQueryServices, IRemoteServices remoteServices)
{
_packageName = packageName;
_queryServices = queryServices;
_buildinQueryServices = buildinQueryServices;
_remoteServices = remoteServices;
var operation = new WebPlayModeInitializationOperation(this, packageName);
@ -33,6 +33,16 @@ namespace YooAsset
}
// 下载相关
private List<BundleInfo> ConvertToDownloadList(List<PackageBundle> downloadList)
{
List<BundleInfo> result = new List<BundleInfo>(downloadList.Count);
foreach (var packageBundle in downloadList)
{
var bundleInfo = ConvertToDownloadInfo(packageBundle);
result.Add(bundleInfo);
}
return result;
}
private BundleInfo ConvertToDownloadInfo(PackageBundle packageBundle)
{
string remoteMainURL = _remoteServices.GetRemoteMainURL(packageBundle.FileName);
@ -41,6 +51,12 @@ namespace YooAsset
return bundleInfo;
}
// 查询相关
private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{
return _buildinQueryServices.QueryStreamingAssets(_packageName, packageBundle.FileName);
}
#region IPlayModeServices接口
public PackageManifest ActiveManifest
{
@ -57,11 +73,6 @@ namespace YooAsset
{
}
private bool IsBuildinPackageBundle(PackageBundle packageBundle)
{
return _queryServices.QueryStreamingAssets(_packageName, packageBundle.FileName);
}
UpdatePackageVersionOperation IPlayModeServices.UpdatePackageVersionAsync(bool appendTimeTicks, int timeout)
{
var operation = new WebPlayModeUpdatePackageVersionOperation(this, _packageName, appendTimeTicks, timeout);
@ -83,15 +94,101 @@ namespace YooAsset
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByAll(int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
List<BundleInfo> downloadList = GetDownloadListByAll(_activeManifest);
var operation = new ResourceDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
public List<BundleInfo> GetDownloadListByAll(PackageManifest manifest)
{
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList)
{
// 忽略APP资源
if (IsBuildinPackageBundle(packageBundle))
continue;
downloadList.Add(packageBundle);
}
return ConvertToDownloadList(downloadList);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByTags(string[] tags, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
List<BundleInfo> downloadList = GetDownloadListByTags(_activeManifest, tags);
var operation = new ResourceDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
public List<BundleInfo> GetDownloadListByTags(PackageManifest manifest, string[] tags)
{
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in manifest.BundleList)
{
// 忽略APP资源
if (IsBuildinPackageBundle(packageBundle))
continue;
// 如果未带任何标记,则统一下载
if (packageBundle.HasAnyTags() == false)
{
downloadList.Add(packageBundle);
}
else
{
// 查询DLC资源
if (packageBundle.HasTag(tags))
{
downloadList.Add(packageBundle);
}
}
}
return ConvertToDownloadList(downloadList);
}
ResourceDownloaderOperation IPlayModeServices.CreateResourceDownloaderByPaths(AssetInfo[] assetInfos, int downloadingMaxNumber, int failedTryAgain, int timeout)
{
return ResourceDownloaderOperation.CreateEmptyDownloader(downloadingMaxNumber, failedTryAgain, timeout);
List<BundleInfo> downloadList = GetDownloadListByPaths(_activeManifest, assetInfos);
var operation = new ResourceDownloaderOperation(downloadList, downloadingMaxNumber, failedTryAgain, timeout);
return operation;
}
public List<BundleInfo> GetDownloadListByPaths(PackageManifest manifest, AssetInfo[] assetInfos)
{
// 获取资源对象的资源包和所有依赖资源包
List<PackageBundle> checkList = new List<PackageBundle>();
foreach (var assetInfo in assetInfos)
{
if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
continue;
}
// 注意:如果清单里未找到资源包会抛出异常!
PackageBundle mainBundle = manifest.GetMainPackageBundle(assetInfo.AssetPath);
if (checkList.Contains(mainBundle) == false)
checkList.Add(mainBundle);
// 注意:如果清单里未找到资源包会抛出异常!
PackageBundle[] dependBundles = manifest.GetAllDependencies(assetInfo.AssetPath);
foreach (var dependBundle in dependBundles)
{
if (checkList.Contains(dependBundle) == false)
checkList.Add(dependBundle);
}
}
List<PackageBundle> downloadList = new List<PackageBundle>(1000);
foreach (var packageBundle in checkList)
{
// 忽略APP资源
if (IsBuildinPackageBundle(packageBundle))
continue;
downloadList.Add(packageBundle);
}
return ConvertToDownloadList(downloadList);
}
ResourceUnpackerOperation IPlayModeServices.CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout)
@ -102,6 +199,11 @@ namespace YooAsset
{
return ResourceUnpackerOperation.CreateEmptyUnpacker(upackingMaxNumber, failedTryAgain, timeout);
}
ResourceImporterOperation IPlayModeServices.CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout)
{
return ResourceImporterOperation.CreateEmptyImporter(importerMaxNumber, failedTryAgain, timeout);
}
#endregion
#region IBundleServices接口

View File

@ -122,7 +122,8 @@ namespace YooAsset
var initializeParameters = parameters as HostPlayModeParameters;
initializeOperation = hostPlayModeImpl.InitializeAsync(
PackageName,
initializeParameters.QueryServices,
initializeParameters.BuildinQueryServices,
initializeParameters.DeliveryQueryServices,
initializeParameters.RemoteServices
);
}
@ -138,7 +139,7 @@ namespace YooAsset
var initializeParameters = parameters as WebPlayModeParameters;
initializeOperation = webPlayModeImpl.InitializeAsync(
PackageName,
initializeParameters.QueryServices,
initializeParameters.BuildinQueryServices,
initializeParameters.RemoteServices
);
}
@ -187,8 +188,10 @@ namespace YooAsset
if (parameters is HostPlayModeParameters)
{
var hostPlayModeParameters = parameters as HostPlayModeParameters;
if (hostPlayModeParameters.QueryServices == null)
throw new Exception($"{nameof(IQueryServices)} is null.");
if (hostPlayModeParameters.BuildinQueryServices == null)
throw new Exception($"{nameof(IBuildinQueryServices)} is null.");
if (hostPlayModeParameters.DeliveryQueryServices == null)
throw new Exception($"{nameof(IDeliveryQueryServices)} is null.");
if (hostPlayModeParameters.RemoteServices == null)
throw new Exception($"{nameof(IRemoteServices)} is null.");
}
@ -205,11 +208,19 @@ namespace YooAsset
else
throw new NotImplementedException();
// 检测运行平台
if (_playMode == EPlayMode.HostPlayMode || _playMode == EPlayMode.OfflinePlayMode)
// 检测运行平台
if (_playMode != EPlayMode.EditorSimulateMode)
{
#if UNITY_WEBGL
throw new Exception($"WebGL plateform not support : {_playMode} ! Please use {nameof(EPlayMode.WebPlayMode)}");
if (_playMode != EPlayMode.WebPlayMode)
{
throw new Exception($"{_playMode} can not support WebGL plateform ! Please use {nameof(EPlayMode.WebPlayMode)}");
}
#else
if (_playMode == EPlayMode.WebPlayMode)
{
throw new Exception($"{nameof(EPlayMode.WebPlayMode)} only support WebGL plateform !");
}
#endif
}
@ -238,7 +249,7 @@ namespace YooAsset
/// <param name="timeout">超时时间默认值60秒</param>
public UpdatePackageVersionOperation UpdatePackageVersionAsync(bool appendTimeTicks = true, int timeout = 60)
{
DebugCheckInitialize();
DebugCheckInitialize(false);
return _playModeServices.UpdatePackageVersionAsync(appendTimeTicks, timeout);
}
@ -250,7 +261,7 @@ namespace YooAsset
/// <param name="timeout">超时时间默认值60秒</param>
public UpdatePackageManifestOperation UpdatePackageManifestAsync(string packageVersion, bool autoSaveVersion = true, int timeout = 60)
{
DebugCheckInitialize();
DebugCheckInitialize(false);
DebugCheckUpdateManifest();
return _playModeServices.UpdatePackageManifestAsync(packageVersion, autoSaveVersion, timeout);
}
@ -262,7 +273,7 @@ namespace YooAsset
/// <param name="timeout">超时时间默认值60秒</param>
public PreDownloadContentOperation PreDownloadContentAsync(string packageVersion, int timeout = 60)
{
DebugCheckInitialize();
DebugCheckInitialize(false);
return _playModeServices.PreDownloadContentAsync(packageVersion, timeout);
}
@ -288,14 +299,23 @@ namespace YooAsset
return operation;
}
/// <summary>
/// 获取指定版本的缓存信息
/// </summary>
public GetAllCacheFileInfosOperation GetAllCacheFileInfosAsync(string packageVersion, int timeout = 60)
{
DebugCheckInitialize();
var operation = new GetAllCacheFileInfosOperation(PackageName);
OperationSystem.StartOperation(operation);
return operation;
}
/// <summary>
/// 获取本地包裹的版本信息
/// </summary>
public string GetPackageVersion()
{
DebugCheckInitialize();
if (_playModeServices.ActiveManifest == null)
return string.Empty;
return _playModeServices.ActiveManifest.PackageVersion;
}
@ -326,7 +346,7 @@ namespace YooAsset
{
DebugCheckInitialize();
var persistent = PersistentTools.GetPersistent(PackageName);
return persistent.BuildinRoot;
return persistent.BuildinPackageRoot;
}
/// <summary>
@ -336,7 +356,17 @@ namespace YooAsset
{
DebugCheckInitialize();
var persistent = PersistentTools.GetPersistent(PackageName);
return persistent.SandboxRoot;
return persistent.SandboxPackageRoot;
}
/// <summary>
/// 获取包裹的沙盒文件AB文件的缓存目录
/// </summary>
public string GetPackageSandboxCacheBundleRootDirectory()
{
DebugCheckInitialize();
var persistent = PersistentTools.GetPersistent(PackageName);
return persistent.SandboxCacheBundleFilesRoot;
}
/// <summary>
@ -359,17 +389,7 @@ namespace YooAsset
{
DebugCheckInitialize();
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, null);
if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
return false;
}
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
return true;
else
return false;
return IsNeedDownloadFromRemoteInternal(assetInfo);
}
/// <summary>
@ -379,17 +399,7 @@ namespace YooAsset
public bool IsNeedDownloadFromRemote(AssetInfo assetInfo)
{
DebugCheckInitialize();
if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
return false;
}
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
return true;
else
return false;
return IsNeedDownloadFromRemoteInternal(assetInfo);
}
/// <summary>
@ -443,6 +453,28 @@ namespace YooAsset
string assetPath = _playModeServices.ActiveManifest.TryMappingToAssetPath(location);
return string.IsNullOrEmpty(assetPath) == false;
}
private bool IsNeedDownloadFromRemoteInternal(AssetInfo assetInfo)
{
if (assetInfo.IsInvalid)
{
YooLogger.Warning(assetInfo.Error);
return false;
}
BundleInfo bundleInfo = _bundleServices.GetBundleInfo(assetInfo);
if (bundleInfo.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
return true;
BundleInfo[] depends = _bundleServices.GetAllDependBundleInfos(assetInfo);
foreach (var depend in depends)
{
if (depend.LoadMode == BundleInfo.ELoadMode.LoadFromRemote)
return true;
}
return false;
}
#endregion
#region 原生文件
@ -573,6 +605,18 @@ namespace YooAsset
return LoadAssetInternal(assetInfo, true);
}
/// <summary>
/// 同步加载资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public AssetOperationHandle LoadAssetSync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadAssetInternal(assetInfo, true);
}
/// <summary>
/// 异步加载资源对象
@ -608,6 +652,18 @@ namespace YooAsset
return LoadAssetInternal(assetInfo, false);
}
/// <summary>
/// 异步加载资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public AssetOperationHandle LoadAssetAsync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadAssetInternal(assetInfo, false);
}
private AssetOperationHandle LoadAssetInternal(AssetInfo assetInfo, bool waitForAsyncComplete)
{
@ -662,6 +718,18 @@ namespace YooAsset
return LoadSubAssetsInternal(assetInfo, true);
}
/// <summary>
/// 同步加载子资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public SubAssetsOperationHandle LoadSubAssetsSync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadSubAssetsInternal(assetInfo, true);
}
/// <summary>
/// 异步加载子资源对象
@ -697,6 +765,18 @@ namespace YooAsset
return LoadSubAssetsInternal(assetInfo, false);
}
/// <summary>
/// 异步加载子资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public SubAssetsOperationHandle LoadSubAssetsAsync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadSubAssetsInternal(assetInfo, false);
}
private SubAssetsOperationHandle LoadSubAssetsInternal(AssetInfo assetInfo, bool waitForAsyncComplete)
{
@ -751,6 +831,18 @@ namespace YooAsset
return LoadAllAssetsInternal(assetInfo, true);
}
/// <summary>
/// 同步加载资源包内所有资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public AllAssetsOperationHandle LoadAllAssetsSync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadAllAssetsInternal(assetInfo, true);
}
/// <summary>
/// 异步加载资源包内所有资源对象
@ -786,6 +878,18 @@ namespace YooAsset
return LoadAllAssetsInternal(assetInfo, false);
}
/// <summary>
/// 异步加载资源包内所有资源对象
/// </summary>
/// <param name="location">资源的定位地址</param>
public AllAssetsOperationHandle LoadAllAssetsAsync(string location)
{
DebugCheckInitialize();
Type type = typeof(UnityEngine.Object);
AssetInfo assetInfo = ConvertLocationToAssetInfo(location, type);
return LoadAllAssetsInternal(assetInfo, false);
}
private AllAssetsOperationHandle LoadAllAssetsInternal(AssetInfo assetInfo, bool waitForAsyncComplete)
{
@ -943,6 +1047,21 @@ namespace YooAsset
}
#endregion
#region 资源导入
/// <summary>
/// 创建资源导入器
/// 注意:资源文件名称必须和资源服务器部署的文件名称一致!
/// </summary>
/// <param name="filePaths">资源路径列表</param>
/// <param name="importerMaxNumber">同时导入的最大文件数</param>
/// <param name="failedTryAgain">导入失败的重试次数</param>
public ResourceImporterOperation CreateResourceImporter(string[] filePaths, int importerMaxNumber, int failedTryAgain)
{
DebugCheckInitialize();
return _playModeServices.CreateResourceImporterByFilePaths(filePaths, importerMaxNumber, failedTryAgain, int.MaxValue);
}
#endregion
#region 内部方法
/// <summary>
/// 是否包含资源文件
@ -967,12 +1086,18 @@ namespace YooAsset
#region 调试方法
[Conditional("DEBUG")]
private void DebugCheckInitialize()
private void DebugCheckInitialize(bool checkActiveManifest = true)
{
if (_initializeStatus == EOperationStatus.None)
throw new Exception("Package initialize not completed !");
else if (_initializeStatus == EOperationStatus.Failed)
throw new Exception($"Package initialize failed ! {_initializeError}");
if (checkActiveManifest)
{
if (_playModeServices.ActiveManifest == null)
throw new Exception("Not found active manifest !");
}
}
[Conditional("DEBUG")]

View File

@ -1,10 +1,10 @@

namespace YooAsset
{
public interface IQueryServices
public interface IBuildinQueryServices
{
/// <summary>
/// 查询内置资源
/// 查询应用程序里的内置资源是否存在
/// </summary>
bool QueryStreamingAssets(string packageName, string fileName);
}

View File

@ -0,0 +1,25 @@

namespace YooAsset
{
/// <summary>
/// 分发的资源信息
/// </summary>
public struct DeliveryFileInfo
{
public string DeliveryFilePath;
public ulong DeliveryFileOffset;
}
public interface IDeliveryQueryServices
{
/// <summary>
/// 查询是否为开发者分发的资源
/// </summary>
bool QueryDeliveryFiles(string packageName, string fileName);
/// <summary>
/// 获取开发者分发的资源信息
/// </summary>
DeliveryFileInfo GetDeliveryFileInfo(string packageName, string fileName);
}
}

View File

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

View File

@ -36,5 +36,8 @@ namespace YooAsset
// 解压相关
ResourceUnpackerOperation CreateResourceUnpackerByAll(int upackingMaxNumber, int failedTryAgain, int timeout);
ResourceUnpackerOperation CreateResourceUnpackerByTags(string[] tags, int upackingMaxNumber, int failedTryAgain, int timeout);
// 导入相关
ResourceImporterOperation CreateResourceImporterByFilePaths(string[] filePaths, int importerMaxNumber, int failedTryAgain, int timeout);
}
}

View File

@ -10,6 +10,10 @@ namespace YooAsset
/// </summary>
public string ManifestFileName = "PackageManifest";
/// <summary>
/// 默认的YooAsset文件夹名称
/// </summary>
public string DefaultYooFolderName = "yoo";
/// <summary>
/// 清单文件头标记
@ -37,11 +41,6 @@ namespace YooAsset
/// </summary>
public const string CacheBundleInfoFileName = "__info";
/// <summary>
/// 默认的YooAsset文件夹名称
/// </summary>
public const string DefaultYooFolderName = "yoo";
/// <summary>
/// 缓存的资源文件的文件夹名称
/// </summary>

View File

@ -1,5 +1,6 @@
{
"name": "YooAsset",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],

View File

@ -69,19 +69,20 @@ internal class FsmInitialize : IStateNode
string fallbackHostServer = GetHostServerURL();
var createParameters = new HostPlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
createParameters.QueryServices = new GameQueryServices();
createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.DeliveryQueryServices = new DefaultDeliveryQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters);
}
// WebGL运行模式
if(playMode == EPlayMode.WebPlayMode)
if (playMode == EPlayMode.WebPlayMode)
{
string defaultHostServer = GetHostServerURL();
string fallbackHostServer = GetHostServerURL();
var createParameters = new WebPlayModeParameters();
createParameters.DecryptionServices = new GameDecryptionServices();
createParameters.QueryServices = new GameQueryServices();
createParameters.BuildinQueryServices = new GameQueryServices();
createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer);
initializationOperation = package.InitializeAsync(createParameters);
}
@ -142,11 +143,11 @@ internal class FsmInitialize : IStateNode
_defaultHostServer = defaultHostServer;
_fallbackHostServer = fallbackHostServer;
}
string IRemoteServices.GetRemoteFallbackURL(string fileName)
string IRemoteServices.GetRemoteMainURL(string fileName)
{
return $"{_defaultHostServer}/{fileName}";
}
string IRemoteServices.GetRemoteMainURL(string fileName)
string IRemoteServices.GetRemoteFallbackURL(string fileName)
{
return $"{_fallbackHostServer}/{fileName}";
}
@ -178,4 +179,19 @@ internal class FsmInitialize : IStateNode
return 1024;
}
}
/// <summary>
/// 默认的分发资源查询服务类
/// </summary>
private class DefaultDeliveryQueryServices : IDeliveryQueryServices
{
public DeliveryFileInfo GetDeliveryFileInfo(string packageName, string fileName)
{
throw new NotImplementedException();
}
public bool QueryDeliveryFiles(string packageName, string fileName)
{
return false;
}
}
}

View File

@ -4,9 +4,9 @@ using UnityEngine;
using YooAsset;
/// <summary>
/// 内置文件查询服务类
/// 资源文件查询服务类
/// </summary>
public class GameQueryServices : IQueryServices
public class GameQueryServices : IBuildinQueryServices
{
public bool QueryStreamingAssets(string packageName, string fileName)
{

View File

@ -7,9 +7,9 @@ using YooAsset;
/*
/// <summary>
/// 内置文件查询服务类
/// 资源文件查询服务类
/// </summary>
public class GameQueryServices2 : IQueryServices
public class GameQueryServices2 : IBuildinQueryServices
{
public bool QueryStreamingAssets(string packageName, string fileName)
{

View File

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