diff --git a/.github/README.md b/.github/README.md index 7c8de60..b123dc8 100644 --- a/.github/README.md +++ b/.github/README.md @@ -1,10 +1,10 @@ ``` - █████╗ ██╗ ██████╗ ██╗ ██╗███╗ ██╗██╗████████╗██╗ ██╗ ██████╗██╗ ██╗ █████╗ ███████╗███████╗███████╗████████╗ - ██╔══██╗██║██╔═══██╗ ██║ ██║████╗ ██║██║╚══██╔══╝╚██╗ ██╔╝ ██╔════╝██║ ██║ ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ - ███████║██║██║ ██║ ██║ ██║██╔██╗ ██║██║ ██║ ╚████╔╝ ██║ ██║ ██║ ███████║███████╗███████╗█████╗ ██║ - ██╔══██║██║██║ ██║ ██║ ██║██║╚██╗██║██║ ██║ ╚██╔╝ ██║ ██║ ██║ ██╔══██║╚════██║╚════██║██╔══╝ ██║ - ██║ ██║██║╚██████╔╝ ╚██████╔╝██║ ╚████║██║ ██║ ██║ ╚██████╗███████╗██║ ██║ ██║███████║███████║███████╗ ██║ - ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ + ██╗ ██╗███╗ ██╗██╗████████╗██╗ ██╗ ██████╗██╗ ██╗ █████╗ ███████╗███████╗███████╗████████╗ + ██║ ██║████╗ ██║██║╚══██╔══╝╚██╗ ██╔╝ ██╔════╝██║ ██║ ██╔══██╗██╔════╝██╔════╝██╔════╝╚══██╔══╝ + ██║ ██║██╔██╗ ██║██║ ██║ ╚████╔╝ ██║ ██║ ██║ ███████║███████╗███████╗█████╗ ██║ + ██║ ██║██║╚██╗██║██║ ██║ ╚██╔╝ ██║ ██║ ██║ ██╔══██║╚════██║╚════██║██╔══╝ ██║ + ╚██████╔╝██║ ╚████║██║ ██║ ██║ ╚██████╗███████╗██║ ██║ ██║███████║███████║███████╗ ██║ + ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═╝ ```

English | 简体中文

diff --git a/.github/qodana.yaml b/.github/qodana.yaml new file mode 100644 index 0000000..d3a7637 --- /dev/null +++ b/.github/qodana.yaml @@ -0,0 +1,35 @@ +#-------------------------------------------------------------------------------# +# Qodana analysis is configured by qodana.yaml file # +# https://www.jetbrains.com/help/qodana/qodana-yaml.html # +#-------------------------------------------------------------------------------# +version: "1.0" +linter: jetbrains/qodana-dotnet:2023.3 +include: + - name: CheckDependencyLicenses + +#Specify IDE code to run analysis without container (Applied in CI/CD pipeline) +ide: QDNET + +#Specify inspection profile for code analysis +profile: + name: qodana.starter + +#Enable inspections +#include: +# - name: + +#Disable inspections +exclude: + - name: All + paths: + - "Resources/Editor" + - "*.meta" + - "*.asmdef" + - "*.tt" + +#Execute shell command before Qodana execution (Applied in CI/CD pipeline) +#bootstrap: sh ./prepare-qodana.sh + +#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline) +#plugins: +# - id: #(plugin id can be found at https://plugins.jetbrains.com) \ No newline at end of file diff --git a/.github/workflows/code_quality.yml b/.github/workflows/code_quality.yml new file mode 100644 index 0000000..ff99505 --- /dev/null +++ b/.github/workflows/code_quality.yml @@ -0,0 +1,30 @@ +name: 🧬 Code Optimize Qodana +on: + workflow_dispatch: + pull_request: + branches: + - main + push: + tags: # 当生成指定标签时触发 + - '*.*.*' + branches: # Specify your branches here + - main + - '1.*' +jobs: + qodana: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + checks: write + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.event.pull_request.head.sha }} # 检查实际的pull请求提交,而不是合并提交 + fetch-depth: 0 # 拉请求分析需要完整的历史记录 + - name: 🧬 Qodana Scan + uses: JetBrains/qodana-action@v2023.3 + with: + pr-mode: false + env: + QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/github-close-stale-issues.yml b/.github/workflows/github-close-stale-issues.yml index 3b28c39..e0d3e38 100644 --- a/.github/workflows/github-close-stale-issues.yml +++ b/.github/workflows/github-close-stale-issues.yml @@ -12,9 +12,9 @@ # Abandoned Issues and Pull Request". # https://igorwiese.com/images/papers/Paper_BotSE_19.pdf -name: GitHub - Close stale issues +name: 🧪 GitHub - Close stale issues on: - schedule: [cron: "50 0 * * 1"] # run weekly Monday 00:50 UTC + schedule: [ cron: "50 0 * * 1" ] # run weekly Monday 00:50 UTC workflow_dispatch: jobs: job-close-stale-issues: @@ -32,8 +32,28 @@ jobs: exempt-issue-labels: 'blocker,bug,enhancement,help wanted,regression' days-before-stale: 90 days-before-close: 30 - stale-issue-message: 'This issue is stale because it has been open for 90 days with no activity. Please remove the stale label or add a comment or this issue will be closed in 30 days.' - stale-pr-message: 'This PR is stale because it has been open for 90 days with no activity. Please remove the stale label or add a comment or this PR will be closed in 30 days.' - close-issue-message: 'This issue was closed because it has been stalled for 30 days with no activity. Please feel free to reopen.' - close-pr-message: 'This PR was closed because it has been stalled for 30 days with no activity. Please feel free to reopen.' + stale-issue-message: | + ### English + This issue is stale because it has been open for 90 days with no activity. + Please remove the stale label or add a comment or this issue will be closed in 30 days. + ### 中文 + 此问题已经打开了90天没有活动,因此已经过时。 + 请删除过时标签或添加评论,否则此问题将在30天内关闭。 + stale-pr-message: | + ### English + This PR is stale because it has been open for 90 days with no activity. + Please remove the stale label or add a comment or this PR will be closed in 30 days. + ### 中文 + 此拉取请求已经打开了90天没有活动,因此已经过时。 + 请删除过时标签或添加评论,否则此拉取请求将在30天内关闭。 + close-issue-message: | + ### English + This issue was closed because it has been stale for 30 days with no activity. Please feel free to reopen. + ### 中文 + 此问题已经过时30天没有活动,因此已经关闭。请随时重新打开。 + close-pr-message: | + ### English + This PR was closed because it has been stale for 30 days with no activity. Please feel free to reopen. + ### 中文 + 此拉取请求已经过时30天没有活动,因此已经关闭。请随时重新打开. repo-token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml index 279ca14..49bbb5c 100644 --- a/.github/workflows/greetings.yml +++ b/.github/workflows/greetings.yml @@ -1,6 +1,6 @@ name: 🧪 CI Greetings -on: [pull_request_target, issues] +on: [ pull_request_target, issues ] jobs: greeting: @@ -9,16 +9,27 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/first-interaction@v1 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - issue-message: "Hello @${{ github.actor }} , thank you for submitting an issue!" - pr-message: "Hello @${{ github.actor }} , thank you submitting a pull request!" - issuesOpened: | - 👋 @{{ author }} Thank you for raising an issue. - We will will investigate into the matter and get back to you as soon as possible. - Please make sure you have given us as much context as possible. - pullRequestOpened: | - 👋 @{{ author }} - Thank you for raising your pull request. - Please make sure you have followed our contributing guidelines. We will review it as soon as possible + - uses: actions/first-interaction@v1 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + issue-message: "Hello @${{ github.actor }} , thank you for submitting an issue!" + pr-message: "Hello @${{ github.actor }} , thank you submitting a pull request!" + issuesOpened: | + ### English + 👋 @{{ author }} Thank you for raising an issue. + We will will investigate into the matter and get back to you as soon as possible. + Please make sure you have given us as much context as possible. + ### 中文 + 👋 @{{ author }} 感谢您提出问题。 + 我们将调查此问题并尽快回复您。 + 请确保您尽可能提供尽可能多的上下文。 + + pullRequestOpened: | + ### English + 👋 @{{ author }} + Thank you for raising your pull request. + Please make sure you have followed our contributing guidelines. We will review it as soon as possible. + ### 中文 + 👋 @{{ author }} + 感谢您提出拉取请求。 + 请确保您已遵循我们的贡献准则。我们将尽快审查它。 \ No newline at end of file diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml index 3675e29..35d9104 100644 --- a/.github/workflows/label.yml +++ b/.github/workflows/label.yml @@ -1,16 +1,15 @@ # This workflow will triage pull requests and apply a label based on the # paths that are modified in the pull request. # -# To use this workflow, you will need to set up a .github/labeler.yml +# To use this workflow, you will need to set up a .github/workflows/labeler.yml # file with configuration. For more information, see: # https://github.com/actions/labeler -name: 🧬 CI Labeler -on: [pull_request_target] +name: 🧪 CI Labeler +on: [ pull_request_target ] jobs: label: - runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/reademe-contributors.yml b/.github/workflows/reademe-contributors.yml index 2e8c388..386e752 100644 --- a/.github/workflows/reademe-contributors.yml +++ b/.github/workflows/reademe-contributors.yml @@ -1,10 +1,8 @@ +name: 🧪 CI Generate a list of contributors on: push: branches: - main - -name: 🧪 CI Generate a list of contributors - jobs: contrib-readme-en-job: runs-on: ubuntu-latest @@ -15,9 +13,9 @@ jobs: with: image_size: 64 readme_path: .github/README.md - use_username: true + use_username: true commit_message: "🤖 [contrib-readme-action] : updated readme" committer_username: "Action Contrib Readme" committer_email: "xinansky99@gmail.com" env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..79aa90c --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,27 @@ +# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. +# +# You can adjust the behavior by modifying this file. +# For more information, see: +# https://github.com/actions/stale +name: Mark stale issues and pull requests + +on: + schedule: + - cron: '30 08 * * *' + +jobs: + stale: + + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + + steps: + - uses: actions/stale@v9 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'Stale issue message' + stale-pr-message: 'Stale pull request message' + stale-issue-label: 'no-issue-activity' + stale-pr-label: 'no-pr-activity' \ No newline at end of file diff --git a/.gitignore b/.gitignore index eb3c77e..96b970e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,22 +5,24 @@ *.git *.vscode +# 编译器 +.git/ +.vs/ +.gradle/ +.idea/ +.vscode/ +.consulo/ + !*.dll.meta !*.asset.meta !*.asmdef.meta !*.cs.meta -.git/ -.vs/ -.idea/ -.gradle/ -.consulo/ [Bb]uild/ [Bb]uilds/ [Tt]emp/ [Oo]bj/ [Ll]ogs/ [Bb]in/ -[Oo]bj/ [Pp]ackages/ [Vv]env/ \ No newline at end of file diff --git a/Editor/Data/AssetBuildConfig.cs b/Editor/Data/AssetBuildConfig.cs index c9a092b..6329698 100644 --- a/Editor/Data/AssetBuildConfig.cs +++ b/Editor/Data/AssetBuildConfig.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel; using System.IO; +using System.Linq; using AIO.UEngine; using UnityEditor; using UnityEngine; @@ -64,28 +65,25 @@ public partial class AssetBuildConfig : ScriptableObject /// public static AssetBuildConfig GetOrCreate() { - if (_instance is null) - { - var objects = EHelper.IO.GetScriptableObjects(); - if (objects != null && objects.Length > 0) - foreach (var asset in objects) - { - if (asset is null) continue; - if (string.IsNullOrEmpty(asset.BuildOutputPath)) - asset.BuildOutputPath = Path.Combine(EHelper.Path.Project, "Bundles"); - - _instance = asset; - break; - } - - if (_instance is null) + if (_instance != null) return _instance; + + var objects = EHelper.IO.GetScriptableObjects(); + if (objects != null && objects.Length > 0) + foreach (var asset in objects.Where(asset => asset)) { - _instance = CreateInstance(); - _instance.BuildOutputPath = Path.Combine(EHelper.Path.Project, "Bundles"); - AssetDatabase.CreateAsset(_instance, "Assets/Editor/ASBuildConfig.asset"); - AssetDatabase.SaveAssets(); + if (string.IsNullOrEmpty(asset.BuildOutputPath)) + asset.BuildOutputPath = Path.Combine(EHelper.Path.Project, "Bundles"); + + _instance = asset; + break; } - } + + if (_instance) return _instance; + + _instance = CreateInstance(); + _instance.BuildOutputPath = Path.Combine(EHelper.Path.Project, "Bundles"); + AssetDatabase.CreateAsset(_instance, "Assets/Editor/ASBuildConfig.asset"); + AssetDatabase.SaveAssets(); return _instance; } diff --git a/Editor/Data/Collect/Root/AssetCollectRoot.Helper.cs b/Editor/Data/Collect/Root/AssetCollectRoot.Helper.cs index d7a1b20..31ca2ea 100644 --- a/Editor/Data/Collect/Root/AssetCollectRoot.Helper.cs +++ b/Editor/Data/Collect/Root/AssetCollectRoot.Helper.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using UnityEditor; using Object = UnityEngine.Object; @@ -114,11 +115,11 @@ public static AssetCollectRoot GetOrCreate() var objects = EHelper.IO.GetScriptableObjects(); if (objects != null && objects.Length > 0) { - foreach (var asset in objects) + foreach (var asset in objects.Where(asset => asset)) { - if (asset is null) continue; if (asset.Packages is null) asset.Packages = Array.Empty(); + _Instance = asset; return _Instance; } @@ -138,11 +139,12 @@ public static AssetCollectRoot GetOrCreate() /// 是否小写 /// 是否包含后缀 /// 限制包名 只查找指定包资源 空则忽略 - /// - /// Item1 包名 - /// Item2 组名 - /// Item3 可寻址路径 - /// + /// + /// var result = AssetCollectRoot.AssetToAddress(); + /// result.Item1 包名 + /// result.Item2 组名 + /// result.Item3 可寻址路径 + /// public static Tuple AssetToAddress(string assetPath, bool isLower, bool hasExtension, string limitPackage = "") { if (IsNoAssetPath(assetPath)) return Empty; diff --git a/Editor/Interface/IAssetRuleFilter/IAssetRuleFilter.cs b/Editor/Interface/IAssetRuleFilter/IAssetRuleFilter.cs index 5acb6ab..34cb2b6 100644 --- a/Editor/Interface/IAssetRuleFilter/IAssetRuleFilter.cs +++ b/Editor/Interface/IAssetRuleFilter/IAssetRuleFilter.cs @@ -11,7 +11,7 @@ public interface IAssetRuleFilter /// 显示顺序 /// int DisplayIndex { get; } - + ///

/// 验证资源是否符合规则 /// diff --git a/Editor/Properties/AssemblyInfo.cs b/Editor/Properties/AssemblyInfo.cs index 36ce6db..5dfec53 100644 --- a/Editor/Properties/AssemblyInfo.cs +++ b/Editor/Properties/AssemblyInfo.cs @@ -1,13 +1,22 @@ -using System.Runtime.CompilerServices; +#region namespace + +using System.Runtime.CompilerServices; using Newtonsoft.Json.Linq; -using UnityEditor.PackageManager; +using UnityEditor; +using UnityEngine; +using PackageInfo = UnityEditor.PackageManager.PackageInfo; [assembly: InternalsVisibleTo("AIO.CLI.YooAsset.Editor")] +#endregion + namespace AIO.UEditor { - internal static class Setting + public static class AssetsEditorSetting { + public const string MENU_ROOT = "AIO/Asset/"; + public const string MENU_ROOT_SETTING = MENU_ROOT + "Setting/"; + /// /// 名称 /// @@ -18,12 +27,109 @@ internal static class Setting /// public static string Version { get; private set; } + #region AutoConversionConfig + + /// + /// 是否自动转换配置 + /// + public static bool AutoConversionConfig; + + private const string MENU_PATH_AUTO_CONVERSION_CONFIG = MENU_ROOT_SETTING + "自动转换配置"; + + [MenuItem(MENU_PATH_AUTO_CONVERSION_CONFIG, true)] + public static bool MenuAutoConversionConfigValidate() + { + Menu.SetChecked(MENU_PATH_AUTO_CONVERSION_CONFIG, AutoConversionConfig); + return true; + } + + [MenuItem(MENU_PATH_AUTO_CONVERSION_CONFIG)] + public static void MenuAutoConversionConfig() + { + AutoConversionConfig = !AutoConversionConfig; + EditorPrefs.SetBool(MENU_PATH_AUTO_CONVERSION_CONFIG, AutoConversionConfig); + if (AutoConversionConfig) Editor.finishedDefaultHeaderGUI += ResInspectorUI.OnPostHeaderGUI; + else Editor.finishedDefaultHeaderGUI -= ResInspectorUI.OnPostHeaderGUI; + } + + #endregion + + #region ShowInspectorAddress + + /// + /// 显示检视器地址 + /// + public static bool ShowInspectorAddress; + + [MenuItem(MENU_PATH_SHOW_INSPECTOR_ADDRESS, true)] + public static bool MenuShowInspectorAddressValidate() + { + Menu.SetChecked(MENU_PATH_SHOW_INSPECTOR_ADDRESS, ShowInspectorAddress); + return true; + } + + private const string MENU_PATH_SHOW_INSPECTOR_ADDRESS = MENU_ROOT_SETTING + "显示检视器地址"; + + [MenuItem(MENU_PATH_SHOW_INSPECTOR_ADDRESS)] + public static void MenuShowInspectorAddress() + { + ShowInspectorAddress = !ShowInspectorAddress; + EditorPrefs.SetBool(MENU_PATH_SHOW_INSPECTOR_ADDRESS, ShowInspectorAddress); + if (ShowInspectorAddress) Editor.finishedDefaultHeaderGUI += ResInspectorUI.OnPostHeaderGUI; + else Editor.finishedDefaultHeaderGUI -= ResInspectorUI.OnPostHeaderGUI; + } + + #endregion + [AInit(EInitAttrMode.Both, int.MaxValue)] - public static void Initialize() + private static void Initialize() { - var package = PackageInfo.FindForAssembly(typeof(Setting).Assembly); + ShowInspectorAddress = EditorPrefs.GetBool(MENU_PATH_SHOW_INSPECTOR_ADDRESS, true); + AutoConversionConfig = EditorPrefs.GetBool(MENU_PATH_AUTO_CONVERSION_CONFIG, true); + + var package = PackageInfo.FindForAssembly(typeof(AssetsEditorSetting).Assembly); var packageJson = AHelper.IO.ReadJsonUTF8(string.Concat(package.resolvedPath, "/package.json")); Version = packageJson.Value("version"); } + + private static SettingsProvider provider; + + /// + /// 创建设置提供者 + /// + [SettingsProvider] + private static SettingsProvider CreateSettingsProvider() + { + if (provider != null) return provider; + + provider = new GraphicSettingsProvider("AIO/Asset System", SettingsScope.User); + provider.label = "Asset System"; + provider.guiHandler = delegate + { + GUILayout.BeginVertical(); + GUILayout.Space(10); + GUILayout.Label("Settings", EditorStyles.boldLabel); + GUILayout.Space(5); + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.LabelField("显示检视器地址"); + if (GUILayout.Button(ShowInspectorAddress ? "开启" : "关闭", EditorStyles.miniButton, GUILayout.Width(50))) + MenuShowInspectorAddress(); + } + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.LabelField("自动转换配置"); + if (GUILayout.Button(AutoConversionConfig ? "开启" : "关闭", EditorStyles.miniButton, GUILayout.Width(50))) + MenuAutoConversionConfig(); + } + + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + EditorGUILayout.LabelField($"Version {Version}", EditorStyles.centeredGreyMiniLabel); + }; + return provider; + } } } \ No newline at end of file diff --git a/Editor/Properties/Language.cs b/Editor/Properties/Language.cs index f9e5591..17906ca 100644 --- a/Editor/Properties/Language.cs +++ b/Editor/Properties/Language.cs @@ -16,10 +16,7 @@ public static event Func FindValue remove => FindValueList.Remove(value); } - static Lang() - { - Tr = new Lang((SystemLanguage)PlayerPrefs.GetInt("AIO.UEditor.Language", (int)Application.systemLanguage)); - } + static Lang() { Tr = new Lang((SystemLanguage)PlayerPrefs.GetInt("AIO.UEditor.Language", (int)Application.systemLanguage)); } public static Lang Tr { get; private set; } @@ -35,15 +32,9 @@ private static string GetValue(SystemLanguage language, string key) private static List> FindValueList = new List>(); - private Lang() - { - Current = Application.systemLanguage; - } + private Lang() { Current = Application.systemLanguage; } - private Lang(SystemLanguage language) - { - Current = language; - } + private Lang(SystemLanguage language) { Current = language; } private Dictionary> Tables = new Dictionary>(); diff --git a/Editor/Proxy/AssetProxyEditor.cs b/Editor/Proxy/AssetProxyEditor.cs index f030f2f..f295375 100644 --- a/Editor/Proxy/AssetProxyEditor.cs +++ b/Editor/Proxy/AssetProxyEditor.cs @@ -21,13 +21,10 @@ public static class AssetProxyEditor [AInit(EInitAttrMode.Both, int.MaxValue)] public static void Initialize() { - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.GetName().Name.EndsWith("Editor"))) { - if (!assembly.GetName().Name.Contains("Editor")) continue; - foreach (var type in assembly.GetTypes()) + foreach (var type in assembly.GetTypes().Where(type => !type.IsAbstract).Where(type => typeof(IAssetProxyEditor).IsAssignableFrom(type))) { - if (type.IsAbstract) continue; - if (!typeof(IAssetProxyEditor).IsAssignableFrom(type)) continue; Editor = (IAssetProxyEditor)Activator.CreateInstance(type); break; } @@ -54,9 +51,7 @@ public static void CreateConfig(string BundlesDir, bool MergeToLatest = false, b /// /// 上传到GCloud /// - public static async Task UploadGCloud( - [ReadOnlyArray] ICollection parameters, - bool isTips = false) + public static async Task UploadGCloud([ReadOnlyArray] ICollection parameters, bool isTips = false) { if (Editor is null) { diff --git a/Editor/Windows/AssetWindow.Helper.cs b/Editor/Windows/AssetWindow.Helper.cs index df9fdce..a644bbb 100644 --- a/Editor/Windows/AssetWindow.Helper.cs +++ b/Editor/Windows/AssetWindow.Helper.cs @@ -6,16 +6,15 @@ namespace AIO.UEditor { - public partial class AssetWindow + partial class AssetWindow { [LnkTools(Tooltip = "AIO 资源管理工具", IconResource = "Editor/Icon/Asset", ShowMode = ELnkShowMode.Toolbar)] public static void OpenWindow() => EditorApplication.ExecuteMenuItem(MENU_WINDOW); - public const string MENU_ROOT = "AIO/Asset/"; - public const string MENU_WINDOW = MENU_ROOT + "Window"; - public const string MENU_CONFIG = MENU_ROOT + "Config"; + public const string MENU_WINDOW = AssetsEditorSetting.MENU_ROOT + "Window"; + public const string MENU_CONFIG = AssetsEditorSetting.MENU_ROOT + "Config"; - [MenuItem(MENU_ROOT + "清空运行时缓存")] + [MenuItem(AssetsEditorSetting.MENU_ROOT + "清空运行时缓存")] public static void ClearRuntimeCache() { var sandbox = Path.Combine(EHelper.Path.Project, ASConfig.GetOrCreate().RuntimeRootDirectory); @@ -23,7 +22,7 @@ public static void ClearRuntimeCache() AHelper.IO.DeleteDir(sandbox, SearchOption.AllDirectories, true); } - [MenuItem(MENU_ROOT + "清空构建时缓存")] + [MenuItem(AssetsEditorSetting.MENU_ROOT + "清空构建时缓存")] public static void ClearBuildCache() { var sandbox = Path.Combine(EHelper.Path.Project, "Bundles"); @@ -101,25 +100,38 @@ public static async void UpdateUploadFirstPack(AssetBuildConfig.GCloudConfig con [InitializeOnLoadMethod] private static void Initialize() { + if (!AssetsEditorSetting.AutoConversionConfig) return; + EditorQuit(); EditorApplication.playModeStateChanged -= EditorQuit; EditorApplication.playModeStateChanged += EditorQuit; } // Unity 第一次进入 Editor 模式时,将 AssetCollectRoot 转换为 AssetProxy - [InitializeOnLoadMethod] private static void EditorQuit() { + if (!AssetsEditorSetting.AutoConversionConfig) + { + EditorApplication.playModeStateChanged -= EditorQuit; + return; + } + var config = ASConfig.GetOrCreate(); if (config.ASMode != EASMode.Editor) return; var root = AssetCollectRoot.GetOrCreate(); - if (root is null) throw new Exception($"Not found {nameof(AssetCollectRoot)}.asset ! Please create it !"); + if (!root) throw new Exception($"Not found {nameof(AssetCollectRoot)}.asset ! Please create it !"); AssetProxyEditor.ConvertConfig(root, false); EditorApplication.playModeStateChanged -= EditorQuit; } private static void EditorQuit(PlayModeStateChange value) { + if (!AssetsEditorSetting.AutoConversionConfig) + { + EditorApplication.playModeStateChanged -= EditorQuit; + return; + } + if (value != PlayModeStateChange.EnteredPlayMode) return; if (!Application.isPlaying) return; @@ -127,7 +139,7 @@ private static void EditorQuit(PlayModeStateChange value) if (config.ASMode != EASMode.Editor) return; var root = AssetCollectRoot.GetOrCreate(); - if (root is null) throw new Exception($"Not found {nameof(AssetCollectRoot)}.asset ! Please create it !"); + if (!root) throw new Exception($"Not found {nameof(AssetCollectRoot)}.asset ! Please create it !"); AssetProxyEditor.ConvertConfig(root, false); EditorApplication.playModeStateChanged -= EditorQuit; } diff --git a/Editor/Windows/AssetWindow.cs b/Editor/Windows/AssetWindow.cs index 4c439ff..d4fe045 100644 --- a/Editor/Windows/AssetWindow.cs +++ b/Editor/Windows/AssetWindow.cs @@ -39,16 +39,15 @@ protected override void OnActivation() if (Pages is null) { Pages = new List(); - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + foreach (var type in from assembly in AppDomain.CurrentDomain.GetAssemblies() + where assembly.FullName.Contains("Editor") + from type in assembly.GetTypes() + where !type.IsAbstract && !type.IsInterface + where typeof(IAssetPage).IsAssignableFrom(type) + select type) { - if (!assembly.FullName.Contains("Editor")) continue; - foreach (var type in assembly.GetTypes()) - { - if (type.IsAbstract || type.IsInterface) continue; - if (!typeof(IAssetPage).IsAssignableFrom(type)) continue; - if (!(Activator.CreateInstance(type) is IAssetPage page)) continue; - Pages.Add(page); - } + if (!(Activator.CreateInstance(type) is IAssetPage page)) continue; + Pages.Add(page); } } @@ -91,7 +90,7 @@ protected override void OnDraw() CurrentPage?.OnDrawContent(DrawRect); } - DrawVersion(Setting.Version); + DrawVersion(AssetsEditorSetting.Version); OnOpenEvent(); } @@ -145,7 +144,8 @@ public int PageIndex } } - public static T OpenPage() where T : IAssetPage + public static T OpenPage() + where T : IAssetPage { if (!Instance) { @@ -157,7 +157,8 @@ public static T OpenPage() where T : IAssetPage return (T)Instance.Pages[Instance.PageIndex]; } - public static bool IsOpenPage() where T : IAssetPage + public static bool IsOpenPage() + where T : IAssetPage { if (!Instance) return false; return Instance.Pages[Instance.PageIndex] is T; diff --git a/Editor/Windows/Helper.cs b/Editor/Windows/Helper.cs index 45d875c..fbdfd5c 100644 --- a/Editor/Windows/Helper.cs +++ b/Editor/Windows/Helper.cs @@ -1,6 +1,7 @@ #region using System; +using System.Collections.Generic; using AIO.UEngine; using UnityEditor; using UnityEngine; @@ -17,6 +18,7 @@ internal class ResInspectorUI { static ResInspectorUI() { + if (!AssetsEditorSetting.ShowInspectorAddress) return; Editor.finishedDefaultHeaderGUI -= OnPostHeaderGUI; Editor.finishedDefaultHeaderGUI += OnPostHeaderGUI; } @@ -32,99 +34,103 @@ private static ASConfig Config private static ASConfig _Config; - private static void OnPostHeaderGUI(Editor editor) + private static readonly List WhiteList = new List { - if (editor.targets.Length != 1) return; - switch (editor.target) - { - case AssetCollectRoot _: - case ASConfig _: - case AssetBuildConfig _: - case ConsoleWindowConfig _: + typeof(AssetCollectRoot).FullName, + typeof(ASConfig).FullName, + typeof(AssetBuildConfig).FullName, + typeof(ConsoleWindowConfig).FullName, #if SUPPORT_YOOASSET - case AssetBundleCollectorSetting _: - case ShaderVariantCollectorSetting _: + typeof(AssetBundleCollectorSetting).FullName, + typeof(ShaderVariantCollectorSetting).FullName, #endif - return; - default: + }; + + internal static void OnPostHeaderGUI(Editor editor) + { + if (!AssetsEditorSetting.ShowInspectorAddress) + { + Editor.finishedDefaultHeaderGUI -= OnPostHeaderGUI; + return; + } - try + if (editor.targets == null) return; + if (editor.targets.Length != 1) return; + if (WhiteList.Contains(editor.target.GetType().FullName)) return; // 判断资源类型 + try + { + if (AssetCollectRoot.ObjToCollector(editor.target, out var result)) + { + using (new EditorGUI.DisabledScope(false)) { - if (AssetCollectRoot.ObjToCollector(editor.target, out var result)) - { - using (new EditorGUI.DisabledScope(false)) - { - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("包名", GUILayout.MaxWidth(65)); - EditorGUILayout.TextField(result.PackageName, GUILayout.MinWidth(30)); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("组名", GUILayout.MaxWidth(65)); - EditorGUILayout.TextField(result.GroupName, GUILayout.MinWidth(30)); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("收集模式", GUILayout.MaxWidth(65)); - result.Type = GELayout.Popup(result.Type, GEStyle.PreDropDown); - GUILayout.EndHorizontal(); - } - - if (result.Type != EAssetCollectItemType.MainAssetCollector) return; - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("寻址规则", GUILayout.MaxWidth(65)); - result.AddressIndex = GELayout.Popup(result.AddressIndex, AssetCollectSetting.MapAddress.Displays, - GEStyle.PreDropDown); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("打包规则", GUILayout.MaxWidth(65)); - result.RulePackIndex = GELayout.Popup(result.RulePackIndex, AssetCollectSetting.MapPacks.Displays, - GEStyle.PreDropDown); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("打包模式", GUILayout.MaxWidth(65)); - result.LoadType = GELayout.Popup(result.LoadType, GEStyle.PreDropDown); - GUILayout.EndHorizontal(); - - - GUILayout.BeginHorizontal(); - EditorGUILayout.LabelField("寻址命名", GUILayout.MaxWidth(65)); - if (Config.LoadPathToLower) - { - using (new EditorGUI.DisabledScope(false)) - result.LocationFormat = GELayout.Popup(EAssetLocationFormat.ToLower, GEStyle.PreDropDown); - } - else - { - result.LocationFormat = GELayout.Popup(result.LocationFormat, GEStyle.PreDropDown); - } - - if (Config.HasExtension) - { - using (new EditorGUI.DisabledScope(false)) - result.HasExtension = GELayout.ToggleLeft("后缀", true, GTOptions.Width(42)); - } - else - { - result.HasExtension = GELayout.ToggleLeft("后缀", result.HasExtension, GTOptions.Width(42)); - } - - GUILayout.EndHorizontal(); - } - else - { - ShowRulePath(AssetCollectRoot.ObjToAddress(editor.target, Config.LoadPathToLower, Config.HasExtension)); - } + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("包名", GUILayout.MaxWidth(65)); + EditorGUILayout.TextField(result.PackageName, GUILayout.MinWidth(30)); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("组名", GUILayout.MaxWidth(65)); + EditorGUILayout.TextField(result.GroupName, GUILayout.MinWidth(30)); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("收集模式", GUILayout.MaxWidth(65)); + result.Type = GELayout.Popup(result.Type, GEStyle.PreDropDown); + GUILayout.EndHorizontal(); } - catch + + if (result.Type != EAssetCollectItemType.MainAssetCollector) return; + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("寻址规则", GUILayout.MaxWidth(65)); + result.AddressIndex = GELayout.Popup(result.AddressIndex, AssetCollectSetting.MapAddress.Displays, + GEStyle.PreDropDown); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("打包规则", GUILayout.MaxWidth(65)); + result.RulePackIndex = GELayout.Popup(result.RulePackIndex, AssetCollectSetting.MapPacks.Displays, + GEStyle.PreDropDown); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("打包模式", GUILayout.MaxWidth(65)); + result.LoadType = GELayout.Popup(result.LoadType, GEStyle.PreDropDown); + GUILayout.EndHorizontal(); + + + GUILayout.BeginHorizontal(); + EditorGUILayout.LabelField("寻址命名", GUILayout.MaxWidth(65)); + if (Config.LoadPathToLower) + { + using (new EditorGUI.DisabledScope(false)) + result.LocationFormat = GELayout.Popup(EAssetLocationFormat.ToLower, GEStyle.PreDropDown); + } + else { - // ignored + result.LocationFormat = GELayout.Popup(result.LocationFormat, GEStyle.PreDropDown); } - break; + if (Config.HasExtension) + { + using (new EditorGUI.DisabledScope(false)) + result.HasExtension = GELayout.ToggleLeft("后缀", true, GTOptions.Width(42)); + } + else + { + result.HasExtension = GELayout.ToggleLeft("后缀", result.HasExtension, GTOptions.Width(42)); + } + + GUILayout.EndHorizontal(); + } + else + { + ShowRulePath(AssetCollectRoot.ObjToAddress(editor.target, Config.LoadPathToLower, Config.HasExtension)); + } + } + catch + { + // ignored } } diff --git a/Editor/Windows/Inspector/AssetConfigCommonEditor.cs b/Editor/Windows/Inspector/AssetConfigCommonEditor.cs index 3b192c2..03bd2e7 100644 --- a/Editor/Windows/Inspector/AssetConfigCommonEditor.cs +++ b/Editor/Windows/Inspector/AssetConfigCommonEditor.cs @@ -156,7 +156,7 @@ private void OnDrawABConfig() if (GUILayout.Button("打开", GEStyle.toolbarbuttonRight)) { AssetWindow.OpenPage(); - EditorApplication.ExecuteMenuItem("AIO/Window/Asset"); + EditorApplication.ExecuteMenuItem(AssetWindow.MENU_WINDOW); } if (GUILayout.Button("构建", GEStyle.toolbarbutton)) AssetProxyEditor.BuildArt(ABConfig); diff --git a/Editor/Windows/Page/4AssetPage.LookCollect.cs b/Editor/Windows/Page/4AssetPage.LookCollect.cs index 9319701..f7cf9f7 100644 --- a/Editor/Windows/Page/4AssetPage.LookCollect.cs +++ b/Editor/Windows/Page/4AssetPage.LookCollect.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using UnityEditor; @@ -43,11 +44,11 @@ public void Dispose() #endregion - private Dictionary DisplayGroupNames; - private Dictionary<(int, int), string[]> CollectorDisplays; - private Dictionary<(int, int), string[]> TypeDisplays; - private Dictionary<(int, int), string[]> TagDisplays; - private Dictionary<(int, int), List> DataDic; + private Dictionary DisplayGroupNames; + private Dictionary<(int, int), string[]> CollectorDisplays; + private Dictionary<(int, int), string[]> TypeDisplays; + private Dictionary<(int, int), string[]> TagDisplays; + private Dictionary<(int, int), ConcurrentBag> DataDic; public void OnDrawHeader(Rect rect) { @@ -193,46 +194,61 @@ private void UpdateDataCollector(int packageIndex, int groupIndex) || Data.Packages[i].Count <= j ) return; - var key = (i, j); - DisplayGroupNames[DisplayPackages[i]] = GetGroupDisPlayNames(Data.Packages[i].Groups); - TagDisplays[key] = Data.Packages[i].Groups[j].Tags; - CollectorDisplays[key] = GetCollectorDisPlayNames(Data.Packages[i].Groups[j].Collectors.GetDisPlayNames()); + var key = (i, j); + var package = Data.Packages[i]; + var group = package.Groups[j]; + + DisplayGroupNames[DisplayPackages[i]] = GetGroupDisPlayNames(package.Groups); + TagDisplays[key] = group.Tags; + CollectorDisplays[key] = GetCollectorDisPlayNames(group.Collectors.GetDisPlayNames()); DisplayCollectorsIndex = 0; - DataDic[key] = new List(); + DataDic[key] = new ConcurrentBag(); TypeDisplays[(i, j)] = Array.Empty(); var toLower = Config.LoadPathToLower; var hasExtension = Config.HasExtension; - var listTypes = new List(); + var listTypes = new ConcurrentBag(); - var count = Data.Packages[i].Groups[j].Collectors.Length; + var count = group.Collectors.Length; var index = 0; - - foreach (var item in Data.Packages[i].Groups[j].Collectors) + + foreach (var item in group.Collectors) { if (item.AllowThread) - Runner.StartTask(() => Collect(item)); + Runner.StartTask(Collect, item); else - Runner.StartCoroutine(() => Collect(item)); + Runner.StartCoroutine(Collect, item); } + TreeViewQueryAsset.Reload(PageValues); return; void Collect(AssetCollectItem item) { - item.CollectAssetAsync(Data.Packages[i], Data.Packages[i].Groups[j], toLower, hasExtension); - DataDic[(i, j)].AddRange(item.DataInfos.Values); + item.CollectAssetAsync(package, group, toLower, hasExtension); + foreach (var variable in item.DataInfos.Values) + { + DataDic[(i, j)].Add(variable); + } + if (count != ++index) return; - Runner.StartCoroutine(() => + + Runner.StartCoroutine(UpdateType, item); + Runner.StartTask(End); + } + + void UpdateType(AssetCollectItem item) + { + foreach (var type in item.DataInfos.Values.Select(dataInfo => dataInfo.Type)) { - listTypes.AddRange(DataDic[(i, j)].Where(dataInfo => !listTypes.Contains(dataInfo.Type)).Select(dataInfo => dataInfo.Type)); - Runner.StartTask(End); - }); + listTypes.Add(type); + } + + TypeDisplays[(i, j)] = listTypes.Distinct().ToArray(); } void End() { - TypeDisplays[(i, j)] = listTypes.ToArray(); lock (PageValues) { PageValues.Add(DataDic[(i, j)].Where(data => !FilterData(data))); @@ -272,7 +288,7 @@ public void UpdateData() if (TagDisplays is null) TagDisplays = new Dictionary<(int, int), string[]>(); if (TypeDisplays is null) TypeDisplays = new Dictionary<(int, int), string[]>(); if (DisplayGroupNames is null) DisplayGroupNames = new Dictionary(); - if (DataDic is null) DataDic = new Dictionary<(int, int), List>(); + if (DataDic is null) DataDic = new Dictionary<(int, int), ConcurrentBag>(); PageValues.Clear(); PageValues.PageIndex = 0; diff --git a/Editor/Windows/Page/AssetPage.Look.cs b/Editor/Windows/Page/AssetPage.Look.cs index 104884f..129f7af 100644 --- a/Editor/Windows/Page/AssetPage.Look.cs +++ b/Editor/Windows/Page/AssetPage.Look.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.IO; using System.Linq; +using System.Threading.Tasks; using AIO.UEngine; using UnityEditor; using UnityEngine; @@ -15,10 +16,7 @@ public partial class AssetPageLook { #region Instance - static AssetPageLook() - { - _Instance = new AssetPageLook(); - } + static AssetPageLook() { _Instance = new AssetPageLook(); } private static AssetPageLook _Instance; private static AssetPageLook Instance => _Instance ?? (_Instance = new AssetPageLook()); @@ -90,7 +88,7 @@ public string Type get { if (string.IsNullOrEmpty(_Type)) return _Type; - _Type = Object is null ? "Unknown" : Object.GetType().FullName; + _Type = !Object ? "Unknown" : Object.GetType().FullName; return _Type; } } @@ -104,7 +102,9 @@ public string Type private readonly Dictionary Dependencies = new Dictionary(); // 依赖资源 - private void OnQueryAsseChanged(int id) + private int TempIndex; + + private async void OnQueryAsseChanged(int id) { Runner.StopCoroutine(OnSelectionChangedRef); if (id < 0) @@ -114,28 +114,31 @@ private void OnQueryAsseChanged(int id) } SelectAssetDataInfo = PageValues.CurrentPageValues[id]; + Dependencies.Clear(); + TempIndex = id; + await Task.Delay(500); + if (TempIndex != id) return; Runner.StartCoroutine(OnSelectionChangedRef); } private IEnumerator OnSelectionChangedRef() { - Dependencies.Clear(); - yield return Runner.WaitForSeconds(0.5f); + yield return Runner.YieldReturn; var assetPath = SelectAssetDataInfo.AssetPath; foreach (var dependency in AssetDatabase.GetDependencies(assetPath)) { if (assetPath == dependency) continue; if (Dependencies.ContainsKey(dependency)) continue; - var info = new DependenciesInfo - { - AssetPath = dependency, Object = AssetDatabase.LoadAssetAtPath(dependency) - }; - if (!info.Object) continue; - DependenciesSize += info.Size = new FileInfo(dependency).Length; - Dependencies.Add(dependency, info); + var obj = AssetDatabase.LoadAssetAtPath(dependency); + if (!obj) continue; + var info = new DependenciesInfo { AssetPath = dependency, Object = obj, Size = new FileInfo(dependency).Length }; + DependenciesSize += info.Size; + Dependencies[dependency] = info; + yield return Runner.YieldReturn; } SelectAsset = AssetDatabase.LoadAssetAtPath(assetPath); + yield return Runner.YieldReturn; TreeViewDependencies.Reload(Dependencies.Values); } @@ -299,7 +302,7 @@ private static void SearchAssetText(Rect rect) #if UNITY_2021_1_OR_NEWER if (!GUI.Button(cell, GUIContent.none, GEStyle.SearchCancelButton)) return; #else - if (!GUI.Button(cell, GUIContent.none, GEStyle.ToolbarSeachCancelButton)) return; + if (!GUI.Button(cell, GUIContent.none, GEStyle.ToolbarSeachCancelButton)) return; #endif GUI.FocusControl(null); @@ -355,7 +358,7 @@ private static bool IsFilterTypes(int index, AssetDataInfo data, ICollection groups) { var page = groups.Count > 15; - return (from t in groups - select t.Name - into groupName - where !string.IsNullOrEmpty(groupName) - select page - ? string.Concat(char.ToUpper(groupName[0]), '/', groupName) - : groupName).ToArray(); + return groups.Select(t => t.Name) + .Where(groupName => !string.IsNullOrEmpty(groupName)) + .Select(groupName => page ? string.Concat(char.ToUpper(groupName[0]), '/', groupName) : groupName) + .ToArray(); } private static string[] GetCollectorDisPlayNames(IList collectors) @@ -633,8 +633,7 @@ private static string[] GetCollectorDisPlayNames(IList collectors) if (collectors.Count > 15) for (var index = 0; index < collectors.Count; index++) - collectors[index] = string.Concat(char.ToUpper(collectors[index][0]), '/', - collectors[index].Replace('/', '\\').TrimEnd('\\')); + collectors[index] = string.Concat(char.ToUpper(collectors[index][0]), '/', collectors[index].Replace('/', '\\').TrimEnd('\\')); else for (var index = 0; index < collectors.Count; index++) collectors[index] = collectors[index].Replace('/', '\\').TrimEnd('\\'); diff --git a/Editor/Windows/TreeView/TreeViewCollect.cs b/Editor/Windows/TreeView/TreeViewCollect.cs index cfeab2a..958f948 100644 --- a/Editor/Windows/TreeView/TreeViewCollect.cs +++ b/Editor/Windows/TreeView/TreeViewCollect.cs @@ -48,7 +48,7 @@ protected override bool OnSorting(int columnIndex, bool ascending) protected override void OnDraw(Rect rect) { - if (Config is null) return; + if (!Config) return; if (Config.Count == 0) return; if (Config.CurrentPackage is null) return; if (Config.CurrentPackage.Count == 0) return; @@ -59,11 +59,12 @@ protected override void OnDraw(Rect rect) protected override void OnBuildRows(TreeViewItem root) { - for (var idxG = 0; idxG < Config?.CurrentGroup?.Count; idxG++) + if (!Config) return; + for (var idxG = 0; idxG < Config.CurrentGroup?.Count; idxG++) { root.AddChild(new TreeViewItemCollect(idxG, Config.CurrentGroup[idxG]) { - OnChangedFold = _ => Reload() + OnChangedFold = _ => Reload(), }); } } diff --git a/Editor/Windows/TreeView/TreeViewDependencies.cs b/Editor/Windows/TreeView/TreeViewDependencies.cs index f873312..17de4bd 100644 --- a/Editor/Windows/TreeView/TreeViewDependencies.cs +++ b/Editor/Windows/TreeView/TreeViewDependencies.cs @@ -30,7 +30,9 @@ protected override bool OnSorting(int col, bool ascending) switch (col) { case 0: - data = ascending ? data.OrderBy(x => x.Object?.name) : data.OrderByDescending(x => x.Object?.name); + data = ascending + ? data.OrderBy(x => x.Object ? x.Object.name : null) + : data.OrderByDescending(x => x.Object ? x.Object.name : null); break; case 1: data = ascending ? data.OrderBy(x => x.Size) : data.OrderByDescending(x => x.Size); diff --git a/Editor/Windows/TreeView/TreeViewGroup.cs b/Editor/Windows/TreeView/TreeViewGroup.cs index abe141f..0f2da8c 100644 --- a/Editor/Windows/TreeView/TreeViewGroup.cs +++ b/Editor/Windows/TreeView/TreeViewGroup.cs @@ -41,7 +41,7 @@ public static TreeViewGroup Create() protected override void OnDraw(Rect rect) { - if (Config is null) return; + if (!Config) return; if (Config.Count == 0) return; if (Config.CurrentPackage is null) return; if (Config.CurrentPackage.Count != 0) return; diff --git a/Editor/Windows/TreeView/TreeViewPackage.cs b/Editor/Windows/TreeView/TreeViewPackage.cs index 86ab73b..27df7ee 100644 --- a/Editor/Windows/TreeView/TreeViewPackage.cs +++ b/Editor/Windows/TreeView/TreeViewPackage.cs @@ -57,8 +57,9 @@ protected override bool OnSorting(int columnIndex, bool ascending) protected override void OnBuildRows(TreeViewItem root) { + if (!Config) return; var isDefault = false; - for (var idxP = 0; idxP < Config?.Count; idxP++) + for (var idxP = 0; idxP < Config.Count; idxP++) { root.AddChild(new TreeViewItemPackage(idxP, Config[idxP])); if (!Config[idxP].Default) continue; @@ -67,7 +68,7 @@ protected override void OnBuildRows(TreeViewItem root) else isDefault = true; } - if (!isDefault && Config?.Count > 0) Config[0].Default = true; + if (!isDefault && Config.Count > 0) Config[0].Default = true; } #region 工具方法 @@ -311,7 +312,7 @@ private void OP_RenameDescription(object obj) protected override void OnDraw(Rect rect) { - if (Config is null) return; + if (!Config) return; if (Config.Count != 0) return; if (GELayout.Button(rect.center, new Vector2(100, 30), "创建资源包")) { diff --git a/Editor/Windows/TreeView/TreeViewQueryAsset.cs b/Editor/Windows/TreeView/TreeViewQueryAsset.cs index 5df5610..10cf53e 100644 --- a/Editor/Windows/TreeView/TreeViewQueryAsset.cs +++ b/Editor/Windows/TreeView/TreeViewQueryAsset.cs @@ -372,7 +372,7 @@ protected override void OnEventKeyDown(Event evt, TreeViewItem item) InvokeSelectionChanged(0); break; } - case KeyCode.RightArrow: // 数字键盘 左键 + case KeyCode.RightArrow: // 数字键盘 左键 { if (PageValues.PageCount <= 1) return; PageValues.PageIndex = PageValues.PageIndex < PageValues.PageCount - 1 ? PageValues.PageIndex + 1 : 0; diff --git a/Editor/Windows/TreeViewItem/TreeViewItemBuildSetting.cs b/Editor/Windows/TreeViewItem/TreeViewItemBuildSetting.cs index 3d6e630..f1c6535 100644 --- a/Editor/Windows/TreeViewItem/TreeViewItemBuildSetting.cs +++ b/Editor/Windows/TreeViewItem/TreeViewItemBuildSetting.cs @@ -18,7 +18,7 @@ public class TreeViewItemBuildSetting : TreeViewItem, ITVItemDraw public TreeViewItemBuildSetting(int id, string displayName, AssetBuildConfig config) : base(id, 1, displayName) { - if (config is null) return; + if (!config) return; BuildConfig = config; Data = AssetCollectRoot.GetOrCreate(); PackageNames = Data.GetNames(); diff --git a/Editor/Windows/TreeViewItem/TreeViewItemGroup.cs b/Editor/Windows/TreeViewItem/TreeViewItemGroup.cs index 6039614..4fb3da8 100644 --- a/Editor/Windows/TreeViewItem/TreeViewItemGroup.cs +++ b/Editor/Windows/TreeViewItem/TreeViewItemGroup.cs @@ -14,7 +14,7 @@ internal sealed class TreeViewItemGroup : TreeViewItem, ITVItemDraw public TreeViewItemGroup(int id, AssetCollectGroup group) : base(id, 2, group.Name) { Group = group; } - private static Texture Icon => _Icon ?? (_Icon = Resources.Load("Editor/Icon/Color/-tutorial-")); + private static Texture Icon => _Icon ? _Icon : _Icon = Resources.Load("Editor/Icon/Color/-tutorial-"); public AssetCollectGroup Group { get; } diff --git a/Editor/Windows/TreeViewItem/TreeViewItemPackage.cs b/Editor/Windows/TreeViewItem/TreeViewItemPackage.cs index 111f970..3a15007 100644 --- a/Editor/Windows/TreeViewItem/TreeViewItemPackage.cs +++ b/Editor/Windows/TreeViewItem/TreeViewItemPackage.cs @@ -13,10 +13,10 @@ internal sealed class TreeViewItemPackage : TreeViewItem, ITVItemDraw public TreeViewItemPackage(int id, AssetCollectPackage package) : base(id, 1, package.Name) { Package = package; } private static Texture _Icon; - private static Texture Icon => _Icon ?? (_Icon = Resources.Load("Editor/Icon/Color/-school-bag")); + private static Texture Icon => _Icon ? _Icon : _Icon = Resources.Load("Editor/Icon/Color/-school-bag"); private static Texture _MainIcon; - private static Texture MainIcon => _MainIcon ?? (_MainIcon = Resources.Load("Editor/Icon/Color/-briefcase")); + private static Texture MainIcon => _MainIcon ? _MainIcon : _MainIcon = Resources.Load("Editor/Icon/Color/-briefcase"); public AssetCollectPackage Package { get; } diff --git a/Extensions/YooAsset.CLI/Editor/1.5.7/AssetProxyEditor.Yoo.157.cs b/Extensions/YooAsset.CLI/Editor/1.5.7/AssetProxyEditor.Yoo.157.cs index c6f8d6e..276e1b1 100644 --- a/Extensions/YooAsset.CLI/Editor/1.5.7/AssetProxyEditor.Yoo.157.cs +++ b/Extensions/YooAsset.CLI/Editor/1.5.7/AssetProxyEditor.Yoo.157.cs @@ -22,15 +22,9 @@ internal partial class AssetProxyEditor_Yoo_157 : IAssetProxyEditor public string Scopes => Ghost.YooAsset.Scopes; public string Name => Ghost.YooAsset.Name; - public bool CreateConfig(string bundlesDir, bool mergeToLatest) - { - return CreateConfig157(bundlesDir, mergeToLatest); - } + public bool CreateConfig(string bundlesDir, bool mergeToLatest) { return CreateConfig157(bundlesDir, mergeToLatest); } - public bool ConvertConfig(AssetCollectRoot config) - { - return ConvertYooAsset.Convert(config); - } + public bool ConvertConfig(AssetCollectRoot config) { return ConvertYooAsset.Convert(config); } public bool BuildArtList(IEnumerable packageNames, AssetBuildCommand command) { @@ -72,10 +66,7 @@ public bool BuildArt(AssetBuildCommand command) /// Tips: /// 需要本地保留一份原始清单 否则会覆盖远端最新的清单文件 导致无法对比 /// - public Task UploadGCloud(ICollection parameters) - { - return UploadGCloudAsync(parameters); - } + public Task UploadGCloud(ICollection parameters) { return UploadGCloudAsync(parameters); } // [LnkTools(IconResource = "Editor/Icon/App/Microsoft")] // public static async void Test() @@ -91,18 +82,12 @@ public Task UploadGCloud(ICollection parameter /// /// 上传到Ftp /// - public async Task UploadFtp(ICollection parameters) - { - return await UploadFtpAsync(parameters); - } + public async Task UploadFtp(ICollection parameters) { return await UploadFtpAsync(parameters); } #endregion [MenuItem("YooAsset/Create Config")] - public static void CreateConfig() - { - CreateConfig157(Path.Combine(EHelper.Path.Project, "Bundles"), AssetBuildConfig.GetOrCreate().MergeToLatest); - } + public static void CreateConfig() { CreateConfig157(Path.Combine(EHelper.Path.Project, "Bundles"), AssetBuildConfig.GetOrCreate().MergeToLatest); } /// /// 创建配置 @@ -121,12 +106,12 @@ private static bool CreateConfig157(string BundlesDir, bool MergeToLatest) if (!Directory.Exists(BundlesConfigDir)) Directory.CreateDirectory(BundlesConfigDir); var BundlesInfo = new DirectoryInfo(BundlesDir); - var Versions = new List(); - var TableDic = new Dictionary>(); + var Versions = new List(); + var TableDic = new Dictionary>(); - foreach (var PlatformInfo in BundlesInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)) + foreach (var PlatformInfo in BundlesInfo.GetDirectories("*", SearchOption.TopDirectoryOnly) + .Where(PlatformInfo => !PlatformInfo.Name.StartsWith("Version"))) { - if (PlatformInfo.Name.StartsWith("Version")) continue; switch (PlatformInfo.Name) { case nameof(BuildTarget.Android): @@ -144,10 +129,10 @@ private static bool CreateConfig157(string BundlesDir, bool MergeToLatest) SearchOption.TopDirectoryOnly)) { Versions.Clear(); - Versions.AddRange(PackageInfo.GetDirectories("*", SearchOption.TopDirectoryOnly). - Where(VersionInfo => !VersionInfo.Name.EndsWith("OutputCache")). - Where(VersionInfo => !VersionInfo.Name.EndsWith("Latest")). - Where(VersionInfo => !VersionInfo.Name.EndsWith("Simulate"))); + Versions.AddRange(PackageInfo.GetDirectories("*", SearchOption.TopDirectoryOnly) + .Where(VersionInfo => !VersionInfo.Name.EndsWith("OutputCache")) + .Where(VersionInfo => !VersionInfo.Name.EndsWith("Latest")) + .Where(VersionInfo => !VersionInfo.Name.EndsWith("Simulate"))); if (Versions.Count <= 0) continue; if (Enum.TryParse(PlatformInfo.Name, out var enums)) @@ -164,9 +149,11 @@ private static bool CreateConfig157(string BundlesDir, bool MergeToLatest) $"BuildReport_{PackageInfo.Name}_{last.Name}.json")); if (table is null) continue; - switch (table.Cast(). - FirstOrDefault(entry => entry.Key.ToString() == "Summary").Value? - .To()? + switch (table.Cast() + .FirstOrDefault(entry => entry.Key.ToString() == "Summary") + .Value? + .To() + ? .Value("CompressOption")) { case (int)ECompressOption.LZMA: @@ -189,9 +176,9 @@ private static bool CreateConfig157(string BundlesDir, bool MergeToLatest) foreach (var pair in TableDic.Where(hashtable => hashtable.Value.Count > 0)) AHelper.IO.WriteJsonUTF8( - Path.Combine(BundlesConfigDir, string.Concat(pair.Key.ToString(), ".json")), - pair.Value.Values.ToArray() - ); + Path.Combine(BundlesConfigDir, string.Concat(pair.Key.ToString(), ".json")), + pair.Value.Values.ToArray() + ); return true; } diff --git a/Extensions/YooAsset.CLI/Editor/1.5.7/Command/YooAssetBuild.cs b/Extensions/YooAsset.CLI/Editor/1.5.7/Command/YooAssetBuild.cs index f20a948..24dfaa7 100644 --- a/Extensions/YooAsset.CLI/Editor/1.5.7/Command/YooAssetBuild.cs +++ b/Extensions/YooAsset.CLI/Editor/1.5.7/Command/YooAssetBuild.cs @@ -22,8 +22,8 @@ public static class YooAssetBuild public static void ArtBuild() { - var cmd = Argument.ResolverCustomCur(); - var args = cmd.executeMethod; + var cmd = Argument.ResolverCustomCur(); + var args = cmd.executeMethod; var buildArgs = Argument.ResolverCustom(args); Lang.Tr.Current = Application.systemLanguage; if (string.IsNullOrEmpty(buildArgs.BuildPackage)) @@ -93,33 +93,31 @@ public static YBuildResult ArtBuild(AssetBuildCommand command) break; case EBuildMode.IncrementalBuild: var target = Path.Combine( - command.OutputRoot, - command.ActiveTarget.ToString(), - command.BuildPackage); + command.OutputRoot, + command.ActiveTarget.ToString(), + command.BuildPackage); if (Directory.Exists(target)) { - var dirs = Directory.GetDirectories(target). - Where(directory => - !directory.EndsWith("Simulate") && - !directory.EndsWith("OutputCache")). - ToArray(); + var dirs = Directory.GetDirectories(target) + .Where(directory => !directory.EndsWith("Simulate") && !directory.EndsWith("OutputCache")) + .ToArray(); if (dirs.Length > 0) { - // 如果为增量更新 则判断是否需要清理缓存 + // 如果为增量更新 则判断是否需要清理缓存 buildMode = YooAsset.Editor.EBuildMode.IncrementalBuild; var cleanCacheNum = AssetBuildConfig.GetOrCreate().AutoCleanCacheNumber; if (dirs.Length >= cleanCacheNum) { var caches = dirs.Sort((s, t) => // 如果缓存数量大于等于设置的缓存数量 则清理缓存 缓存清理机制为删除最早的缓存 { - var st = Directory.GetCreationTimeUtc(s); - var tt = Directory.GetCreationTimeUtc(t); + var st = Directory.GetCreationTimeUtc(s); + var tt = Directory.GetCreationTimeUtc(t); var result = tt.CompareTo(st); if (result == 0) // 如果时间相同 则比较名称 result = string.Compare( - Path.GetFileName(s), - Path.GetFileName(t), - StringComparison.CurrentCulture); + Path.GetFileName(s), + Path.GetFileName(t), + StringComparison.CurrentCulture); return result; }); @@ -160,8 +158,8 @@ public static YBuildResult ArtBuild(AssetBuildCommand command) PackageVersion = command.PackageVersion, BuildOutputRoot = command.OutputRoot, StreamingAssetsRoot = Path.Combine( - Application.streamingAssetsPath, - ASConfig.GetOrCreate().RuntimeRootDirectory), + Application.streamingAssetsPath, + ASConfig.GetOrCreate().RuntimeRootDirectory), DisableWriteTypeTree = false }; switch (command.OutputNameStyle) @@ -205,14 +203,14 @@ public static YBuildResult ArtBuild(AssetBuildCommand command) Debug.Log(AHelper.Json.Serialize(buildParameters)); - var builder = new AssetBundleBuilder(); + var builder = new AssetBundleBuilder(); var buildResult = builder.Run(buildParameters); if (buildResult.Success) { var output = Path.Combine( - buildParameters.BuildOutputRoot, - buildParameters.BuildTarget.ToString(), - buildParameters.PackageName); + buildParameters.BuildOutputRoot, + buildParameters.BuildTarget.ToString(), + buildParameters.PackageName); if (command.MergeToLatest) MergeToLatest(output, buildParameters.PackageVersion); else ManifestGenerate(Path.Combine(output, buildParameters.PackageVersion)); @@ -237,20 +235,21 @@ private static void ManifestGenerate(string dir, bool isAgain = false) return; } - var hashtable = AHelper.IO.GetFilesRelative(dir, "*.*", SearchOption.AllDirectories). - Where(filePath => filePath != Manifest).ToDictionary(filePath => filePath, - filePath => AHelper.IO.GetFileMD5(Path.Combine(dir, filePath))); + var hashtable = AHelper.IO.GetFilesRelative(dir, "*.*", SearchOption.AllDirectories) + .Where(filePath => filePath != Manifest) + .ToDictionary(filePath => filePath, + filePath => AHelper.IO.GetFileMD5(Path.Combine(dir, filePath))); hashtable.Remove("OutputCache"); hashtable.Remove("OutputCache.manifest"); - var versionName = dir.Replace("\\", "/"); + var versionName = dir.Replace("\\", "/"); var versionNameIndex = versionName.LastIndexOf('/'); - var version = versionName.Substring(versionNameIndex + 1); + var version = versionName.Substring(versionNameIndex + 1); - var packageName = dir.PathGetLastFloder().Replace("\\", "/"); + var packageName = dir.PathGetLastFloder().Replace("\\", "/"); var packageNameIndex = packageName.LastIndexOf('/'); - var package = packageName.Substring(packageNameIndex + 1); - var key = $"PackageManifest_{package}.version"; + var package = packageName.Substring(packageNameIndex + 1); + var key = $"PackageManifest_{package}.version"; hashtable.Remove($"BuildReport_{package}_{version}.json"); hashtable[key] = AHelper.IO.GetFileMD5(Path.Combine(dir, key)); AHelper.IO.WriteJson(manifestPath, hashtable.Sort()); @@ -280,10 +279,9 @@ public static Tuple< target.Remove("OutputCache"); target.Remove("OutputCache.manifest"); - var delete = new Dictionary(); // 删除 - var change = new Dictionary(); // 修改 - var add = current.Where(item => !target.ContainsKey(item.Key)). - ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()); // 新增 + var delete = new Dictionary(); // 删除 + var change = new Dictionary(); // 修改 + var add = current.Where(item => !target.ContainsKey(item.Key)).ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()); // 新增 foreach (var item in target) // 遍历最新版本清单 { @@ -321,13 +319,13 @@ public static Tuple< ComparisonManifest(string currentPath, string latestPath) { var current = AHelper.IO.ReadJson>(Path.Combine(currentPath, Manifest)); - var latest = AHelper.IO.ReadJson>(Path.Combine(latestPath, Manifest)); + var latest = AHelper.IO.ReadJson>(Path.Combine(latestPath, Manifest)); return ComparisonManifest(current, latest); } private static void MergeToLatestExe(string currentPath, string latestPath, string latestManifestPath) { - var tuple = ComparisonManifest(currentPath, latestPath); + var tuple = ComparisonManifest(currentPath, latestPath); var latest = AHelper.IO.ReadJson>(latestManifestPath); foreach (var pair in tuple.Item2) // 删除 diff --git a/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.AIOFilterRule.cs b/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.AIOFilterRule.cs index 0dc0c4b..a9de926 100644 --- a/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.AIOFilterRule.cs +++ b/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.AIOFilterRule.cs @@ -20,7 +20,7 @@ private static ASConfig Config { get { - if (_Config is null) _Config = ASConfig.GetOrCreate(); + if (!_Config) _Config = ASConfig.GetOrCreate(); return _Config; } } @@ -40,7 +40,7 @@ private static IFilterRule Rule public bool IsCollectAsset(FilterRuleData data) { if (Application.isPlaying) return Rule.IsCollectAsset(data); - if (Instance is null || !data.UserData.Contains('#')) return false; + if (!Instance || !data.UserData.Contains('#')) return false; var info = data.UserData.SplitOnce('#'); var collector = Instance.GetByName(info.Item1)?.GetByGroupName(info.Item2)?.GetByPath(data.CollectPath); if (collector is null) return false; @@ -92,7 +92,7 @@ private static ASConfig Config { get { - if (_Config is null) _Config = ASConfig.GetOrCreate(); + if (!_Config) _Config = ASConfig.GetOrCreate(); return _Config; } } @@ -101,13 +101,13 @@ private static ASConfig Config public bool IsCollectAsset(FilterRuleData data) { - if (Instance is null || !data.GroupName.Contains('#')) return false; + if (!Instance || !data.GroupName.Contains('#')) return false; var info = data.GroupName.SplitOnce('#'); if (!Application.isPlaying && - (Config.EnableSequenceRecord && - Config.SequenceRecord.ContainsAssetPath(data.AssetPath, info.Item1))) - return false; + Config.EnableSequenceRecord && + Config.SequenceRecord.ContainsAssetPath(data.AssetPath, info.Item1) + ) return false; var collector = Instance.GetByName(info.Item1)?.GetByGroupName(info.Item2)?.GetByPath(data.CollectPath); if (collector is null) return false; diff --git a/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.cs b/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.cs index 6ba9f15..6dcaa8f 100644 --- a/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.cs +++ b/Extensions/YooAsset.CLI/Editor/1.5.7/ConvertYooAsset.cs @@ -21,7 +21,7 @@ private static AssetCollectRoot Instance { get { - if (_Instance is null) _Instance = AssetCollectRoot.GetOrCreate(); + if (!_Instance) _Instance = AssetCollectRoot.GetOrCreate(); return _Instance; } } diff --git a/Extensions/YooAsset.CLI/Editor/1.5.7/Windows/BuildExportGraphWindows.cs b/Extensions/YooAsset.CLI/Editor/1.5.7/Windows/BuildExportGraphWindows.cs index 2a3edcb..a819ec6 100644 --- a/Extensions/YooAsset.CLI/Editor/1.5.7/Windows/BuildExportGraphWindows.cs +++ b/Extensions/YooAsset.CLI/Editor/1.5.7/Windows/BuildExportGraphWindows.cs @@ -70,8 +70,7 @@ public YooAssetGraphicRect() Commond.BuildPipeline = EBuildPipeline.BuiltinBuildPipeline; #endif - YooAssetPackages = AssetBundleCollectorSettingData.Setting.Packages.Select(package => package.PackageName). - ToArray(); + YooAssetPackages = AssetBundleCollectorSettingData.Setting.Packages.Select(package => package.PackageName).ToArray(); YooAssetEncryptions = EditorTools.GetAssignableTypes(typeof(IEncryptionServices)); YooAssetEncryptions.Insert(0, null); YooAssetEncryptionsName = new string[YooAssetEncryptions.Count]; @@ -166,10 +165,9 @@ protected void OnDrawBuildInFile() GELayout.Label("项目导出工程路径", GTOptions.Width(true)); EngineeringPathPath[BuildTarget].VersionIndex = GELayout.Popup( - EngineeringPathPath[BuildTarget]. - VersionIndex, - YooAssetUnityArgs.Versions, - GTOptions.Width(50)); + EngineeringPathPath[BuildTarget].VersionIndex, + YooAssetUnityArgs.Versions, + GTOptions.Width(50)); if (GELayout.Button("Select", GTOptions.Width(50))) { @@ -188,8 +186,7 @@ protected void OnDrawBuildInFile() using (GELayout.VHorizontal()) { EngineeringPathPath[BuildTarget].OutputRoot = GELayout.Field( - EngineeringPathPath[BuildTarget]. - OutputRoot); + EngineeringPathPath[BuildTarget].OutputRoot); } } @@ -209,8 +206,7 @@ public void UpdateTarget() if (!EngineeringPathPath.ContainsKey(BuildTarget)) EngineeringPathPath.Add(BuildTarget, new YooAssetUnityArgs(BuildTarget)); - BuildInFilePlatform = Path.Combine(Commond.OutputRoot, BuildTarget.ToString()). - Replace('/', Path.DirectorySeparatorChar); + BuildInFilePlatform = Path.Combine(Commond.OutputRoot, BuildTarget.ToString()).Replace('/', Path.DirectorySeparatorChar); YooAssetPackageNames = AHelper.IO.GetDirsName(BuildInFilePlatform).ToList(); Commond.PackageVersion = DateTime.Now.ToString("yyyy-MM-dd-HHmmss"); @@ -218,10 +214,7 @@ public void UpdateTarget() EHelper.Prefs.SaveJson(nameof(YooAssetBuildCommand), Commond); } - protected override void OnDrawRight(Rect rect) - { - OnDrawRight(rect.width / 2, rect.width / 4); - } + protected override void OnDrawRight(Rect rect) { OnDrawRight(rect.width / 2, rect.width / 4); } public void OnDrawRight(float widthHalf, float widthQuarter) { @@ -254,10 +247,10 @@ private void Command0() if (GELayout.Button("组合资源包\n目标工程", 100, 25)) { var dic = YooAssetPackageTarget.ToDictionary( - target => target, - target => - YooAssetPackageVersionTarget[target] - [YooAssetPackageTargetIndex[target]]); + target => target, + target => + YooAssetPackageVersionTarget[target] + [YooAssetPackageTargetIndex[target]]); EngineeringPathPath[BuildTarget].BuiltUp(BuildTarget, BuildInFilePlatform, dic); Commond.PackageVersion = DateTime.Now.ToString("yyyy-MM-dd-HHmmss"); } @@ -276,9 +269,7 @@ private async void Upload() OnProgress = progress => { if (EditorUtility.DisplayCancelableProgressBar("Upload FTP", progress.ToString(), - progress.Progress / 100f)) - { - } + progress.Progress / 100f)) { } }, OnError = error => { @@ -329,8 +320,8 @@ private void Command2() if (GELayout.Button("Link", GTOptions.Width(50), GTOptions.Height(25))) { - var source = Commond.OutputRoot.Trim('/', '\\'); - var target = LocalStoragePath.Trim('/', '\\'); + var source = Commond.OutputRoot.Trim('/', '\\'); + var target = LocalStoragePath.Trim('/', '\\'); IExecutor executor = null; if (AHelper.IO.ExistsDir(target)) executor = PrPlatform.Folder.Del(target); @@ -366,10 +357,10 @@ private void Command3() if (GELayout.Button("Pack", GTOptions.Width(50), GTOptions.Height(25))) { var dic = YooAssetPackageTarget.ToDictionary( - target => target, - target => - YooAssetPackageVersionTarget[target] - [YooAssetPackageTargetIndex[target]]); + target => target, + target => + YooAssetPackageVersionTarget[target] + [YooAssetPackageTargetIndex[target]]); EngineeringPathPath[BuildTarget].BuiltUpToStreamingAssets(BuildTarget, BuildInFilePlatform, dic); Commond.PackageVersion = DateTime.Now.ToString("yyyy-MM-dd-HHmmss"); return; @@ -386,8 +377,7 @@ private void Command3() { var package = Path.Combine(BuildInFilePlatform, YooAssetPackageNames[YooAssetPackageIndex]); - var list = AHelper.IO.GetDirsName(package).Where(file => !file.StartsWith("OutputCache")). - ToList(); + var list = AHelper.IO.GetDirsName(package).Where(file => !file.StartsWith("OutputCache")).ToList(); YooAssetPackageVersionTarget.Add(YooAssetPackageNames[YooAssetPackageIndex], list); } @@ -412,8 +402,7 @@ private void Command3() { if (GELayout.Button(YooAssetPackageTarget[j], GTOptions.Width(150))) { - PrPlatform.Open.Path(Path.Combine(BuildInFilePlatform, YooAssetPackageTarget[j])). - Async(); + PrPlatform.Open.Path(Path.Combine(BuildInFilePlatform, YooAssetPackageTarget[j])).Async(); return; } @@ -447,5 +436,4 @@ public override void SaveData() } } - #endif \ No newline at end of file diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Downloader/YAssetProxy.Downloader.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Downloader/YAssetProxy.Downloader.cs index 5f627d1..8a9c047 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Downloader/YAssetProxy.Downloader.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Downloader/YAssetProxy.Downloader.cs @@ -116,23 +116,21 @@ private bool OnWaitBegin() } CurrentValue = CurrentValueDict.Sum(pair => pair.Value); - var endValue = TotalValue - CurrentValue; + var endValue = TotalValue - CurrentValue; var diskSpace = AssetSystem.GetAvailableDiskSpace(); if (diskSpace < endValue) // 检查磁盘空间是否足够 { State = EProgressState.Fail; if (OnDiskSpaceNotEnough is null) throw new SystemException( - $"Out of disk space : {diskSpace.ToConverseStringFileSize()} < {endValue.ToConverseStringFileSize()}"); + $"Out of disk space : {diskSpace.ToConverseStringFileSize()} < {endValue.ToConverseStringFileSize()}"); AssetSystem.LogException( - $"Out of disk space : {diskSpace.ToConverseStringFileSize()} < {endValue.ToConverseStringFileSize()}"); + $"Out of disk space : {diskSpace.ToConverseStringFileSize()} < {endValue.ToConverseStringFileSize()}"); OnDiskSpaceNotEnough.Invoke(Report); return false; } - foreach (var pair in ResourceDownloaderOperations.ToArray().Where(pair => - pair.Value.Status != - EOperationStatus.Succeed)) + foreach (var pair in ResourceDownloaderOperations.ToArray().Where(pair => pair.Value.Status != EOperationStatus.Succeed)) { pair.Value.OnStartDownloadFileCallback = OnStartDownloadFileCallback; pair.Value.OnDownloadProgressCallback = OnUpdateProgress; @@ -140,8 +138,10 @@ private bool OnWaitBegin() continue; void OnUpdateProgress( - int totalDownloadCount, int currentDownloadCount, - long totalDownloadBytes, long currentDownloadBytes) + int totalDownloadCount, + int currentDownloadCount, + long totalDownloadBytes, + long currentDownloadBytes) { if (State != EProgressState.Running) return; switch (Application.internetReachability) @@ -182,7 +182,8 @@ protected override async Task OnWaitAsync() } foreach (var operation in ResourceDownloaderOperations.Values.Where( - operation => !operation.IsDone || operation.Status != EOperationStatus.Succeed)) + operation => !operation.IsDone + || operation.Status != EOperationStatus.Succeed)) { while (State != EProgressState.Running) switch (State) @@ -228,7 +229,8 @@ protected override IEnumerator OnWaitCo() } foreach (var operation in ResourceDownloaderOperations.Values.Where( - operation => !operation.IsDone || operation.Status != EOperationStatus.Succeed)) + operation => !operation.IsDone + || operation.Status != EOperationStatus.Succeed)) { while (State != EProgressState.Running) switch (State) @@ -493,10 +495,7 @@ private void UpdatePackageVersionEnd() private List DownloadTags = new List(); private bool DownloadAll; - public void CollectNeedAll() - { - DownloadAll = true; - } + public void CollectNeedAll() { DownloadAll = true; } public void CollectNeedTag(params string[] tags) { diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Action.UpdatePackages.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Action.UpdatePackages.cs index 2986a99..568eb40 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Action.UpdatePackages.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Action.UpdatePackages.cs @@ -63,8 +63,8 @@ private static bool CheckPackages(string remote, string content, out AssetsPacka return true; } - private static string GetPackageManifestVersionUrl(ASConfig config, AssetsPackageConfig item) - => $"{config.URL}/{AssetSystem.PlatformNameStr}/{item.Name}/{item.Version}/PackageManifest_{item.Name}.version?t={DateTime.Now.Ticks}"; + private static string GetPackageManifestVersionUrl(ASConfig config, AssetsPackageConfig item) => + $"{config.URL}/{AssetSystem.PlatformNameStr}/{item.Name}/{item.Version}/PackageManifest_{item.Name}.version?t={DateTime.Now.Ticks}"; /// /// 更新资源包列表 @@ -77,7 +77,7 @@ private static bool UpdatePackagesRemoteSync(ASConfig config) return false; } - var remote = config.FullURL; + var remote = config.FullURL; string content; try { @@ -95,7 +95,7 @@ private static bool UpdatePackagesRemoteSync(ASConfig config) { item.IsLatest = item.Version == "Latest"; // 如果使用Latest则认为是最新版本 同时需要获取最新版本号 if (!item.IsLatest) continue; - var url = GetPackageManifestVersionUrl(config, item); + var url = GetPackageManifestVersionUrl(config, item); var temp = AHelper.HTTP.Get(url); if (string.IsNullOrEmpty(temp)) { @@ -123,7 +123,7 @@ private static async Task UpdatePackagesRemoteTask(ASConfig config) return false; } - var remote = $"{config.URL}/Version/{AssetSystem.PlatformNameStr}.json?t={DateTime.Now.Ticks}"; + var remote = $"{config.URL}/Version/{AssetSystem.PlatformNameStr}.json?t={DateTime.Now.Ticks}"; string content; try { @@ -142,7 +142,7 @@ private static async Task UpdatePackagesRemoteTask(ASConfig config) { item.IsLatest = item.Version == "Latest"; // 如果使用Latest则认为是最新版本 同时需要获取最新版本号 if (!item.IsLatest) continue; - var url = GetPackageManifestVersionUrl(config, item); + var url = GetPackageManifestVersionUrl(config, item); var temp = await AHelper.HTTP.GetAsync(url); if (string.IsNullOrEmpty(temp)) { @@ -163,8 +163,8 @@ private static async Task UpdatePackagesRemoteTask(ASConfig config) private static bool UpdatePackagesEditor(ASConfig config) { - var assembly = Assembly.Load("AIO.Asset.Editor"); - var type = assembly.GetType("AIO.UEditor.AssetCollectRoot", true); + var assembly = Assembly.Load("AIO.Asset.Editor"); + var type = assembly.GetType("AIO.UEditor.AssetCollectRoot", true); var getOrCreate = type.GetMethod("GetOrCreate", BindingFlags.Static | BindingFlags.Public); var collectRoot = getOrCreate?.Invoke(null, new object[] { }); if (collectRoot is null) @@ -173,18 +173,14 @@ private static bool UpdatePackagesEditor(ASConfig config) return false; } - var packages = type. - GetField("Packages", BindingFlags.Instance | BindingFlags.Public)?. - GetValue(collectRoot); + var packages = type.GetField("Packages", BindingFlags.Instance | BindingFlags.Public)?.GetValue(collectRoot); if (!(packages is Array array)) { AssetSystem.ExceptionEvent(ASException.ASConfigPackagesIsNull); return false; } - var fieldInfo = assembly. - GetType("AIO.UEditor.AssetCollectPackage", true). - GetField("Name", BindingFlags.Instance | BindingFlags.Public); + var fieldInfo = assembly.GetType("AIO.UEditor.AssetCollectPackage", true).GetField("Name", BindingFlags.Instance | BindingFlags.Public); if (fieldInfo is null) { AssetSystem.ExceptionEvent(ASException.ASConfigPackagesIsNull); @@ -215,7 +211,7 @@ from object item in array private static bool UpdatePackagesLocal(ASConfig config) { config.Packages = AHelper.IO.ReadJsonUTF8( - $"{AssetSystem.BuildInRootDirectory}/Version/{AssetSystem.PlatformNameStr}.json"); + $"{AssetSystem.BuildInRootDirectory}/Version/{AssetSystem.PlatformNameStr}.json"); if (config.Packages is null) { AssetSystem.ExceptionEvent(ASException.ASConfigPackagesIsNull); @@ -234,7 +230,7 @@ private static IEnumerator UpdatePackagesRemoteCoroutine(ASConfig config, Action yield break; } - var remote = config.FullURL; + var remote = config.FullURL; var content = string.Empty; using (var uwr = UnityWebRequest.Get(remote)) { @@ -277,7 +273,6 @@ private static IEnumerator UpdatePackagesRemoteCoroutine(ASConfig config, Action cb.Invoke(true); } - private class ActionUpdatePackages : OperationAction { private ASConfig config { get; } @@ -336,7 +331,6 @@ protected override IEnumerator CreateCoroutine() InvokeOnCompleted(); } - /// protected override void CreateSync() { diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.Asset.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.Asset.cs index c1b77c2..6068afd 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.Asset.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.Asset.cs @@ -34,7 +34,8 @@ protected override void CreateSync() Instance.HandleAdd(Address, operation); } - Result = operation?.GetAssetObject(); IsDone = true; + Result = operation?.GetAssetObject(); + IsDone = true; } #endregion @@ -74,10 +75,7 @@ protected override IEnumerator CreateCoroutine() #region Task - private void OnCompletedTaskGeneric() - { - Result = AwaiterGeneric.GetResult(); - } + private void OnCompletedTaskGeneric() { Result = AwaiterGeneric.GetResult(); } private TaskAwaiter AwaiterGeneric; @@ -107,8 +105,8 @@ protected override TaskAwaiter CreateAsync() } /// - public override ILoaderHandle LoadAssetTask(string location, Type type, Action completed = null) - => new LoadAsset(location, type, completed); + public override ILoaderHandle LoadAssetTask(string location, Type type, Action completed = null) => + new LoadAsset(location, type, completed); } } diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.InstGameObject.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.InstGameObject.cs index 84f8ec6..765838d 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.InstGameObject.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Handle/Load.InstGameObject.cs @@ -34,7 +34,8 @@ protected override void CreateSync() Instance.HandleAdd(Address, operation); } - Result = operation.InstantiateSync(parent); IsDone = true; + Result = operation.InstantiateSync(parent); + IsDone = true; } #endregion @@ -74,10 +75,7 @@ protected override IEnumerator CreateCoroutine() #region Task - private void OnCompletedTaskGeneric() - { - Result = AwaiterGeneric.GetResult(); - } + private void OnCompletedTaskGeneric() { Result = AwaiterGeneric.GetResult(); } private TaskAwaiter AwaiterGeneric; diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/Load.Type.Sync.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/Load.Type.Sync.cs index a7af6bc..8262d8f 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/Load.Type.Sync.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/Load.Type.Sync.cs @@ -1,7 +1,6 @@ #if SUPPORT_YOOASSET using System.Linq; -using YooAsset; namespace AIO.UEngine.YooAsset { @@ -48,7 +47,7 @@ private ResPackage AutoGetPackageSync(string packageName, string location) if (!package.CheckLocationValid(location)) { AssetSystem.LogException( - $"[{package.PackageName} : {package.GetPackageVersion()}] 传入地址验证无效 {location}"); + $"[{package.PackageName} : {package.GetPackageVersion()}] 传入地址验证无效 {location}"); return null; } diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/YLoaderHandle.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/YLoaderHandle.cs index 127afd4..f71afcb 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/YLoaderHandle.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Load/YLoaderHandle.cs @@ -2,7 +2,6 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using UnityEngine; namespace AIO.UEngine.YooAsset { diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.Debug.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.Debug.cs index 3754a73..1a9def0 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.Debug.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.Debug.cs @@ -18,34 +18,22 @@ internal class YALogger : ILogger [HideInCallstack] #endif [IgnoreConsoleJump] - public void Log(string message) - { - AssetSystem.Log(message); - } + public void Log(string message) { AssetSystem.Log(message); } #if UNITY_2022_1_OR_NEWER [HideInCallstack] #endif [IgnoreConsoleJump] - public void Warning(string message) - { - AssetSystem.LogWarning(message); - } + public void Warning(string message) { AssetSystem.LogWarning(message); } #if UNITY_2022_1_OR_NEWER [HideInCallstack] #endif [IgnoreConsoleJump] - public void Error(string message) - { - AssetSystem.LogError(message); - } + public void Error(string message) { AssetSystem.LogError(message); } #if UNITY_2022_1_OR_NEWER [HideInCallstack] #endif [IgnoreConsoleJump] - public void Exception(Exception exception) - { - AssetSystem.LogException(exception); - } + public void Exception(Exception exception) { AssetSystem.LogException(exception); } } private enum LoadType @@ -63,8 +51,8 @@ private string GetLocation(string location) { return (from asset in Dic.Values where asset.CheckLocationValid(location) - select asset.GetAssetInfo(location)). - FirstOrDefault()?.AssetPath; + select asset.GetAssetInfo(location)).FirstOrDefault() + ?.AssetPath; } #if UNITY_2022_1_OR_NEWER diff --git a/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.UnLoad.cs b/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.UnLoad.cs index e6fd4f2..09c4b50 100644 --- a/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.UnLoad.cs +++ b/Extensions/YooAsset.CLI/Runtime/1.5.7/Proxy.UnLoad.cs @@ -48,38 +48,31 @@ public override void HandleFree(string location) /// 是否强制回收 public void UnloadUnusedAssets(string packageName, bool isForce = false) { - if (Dic.TryGetValue(packageName, out var value)) - { - if (isForce) - value.Package.ForceUnloadAllAssets(); - else - Runner.StartCoroutine(UnloadUnusedAssetsCo(_ => - { - value.Package.UnloadUnusedAssets(); - AssetSystem.LogFormat(string.Intern("Free Asset Handle Release : {0}"), packageName); - })); - } + if (!Dic.TryGetValue(packageName, out var value)) return; + if (isForce) value.Package.ForceUnloadAllAssets(); + else + Runner.StartCoroutine(UnloadUnusedAssetsCo, (Action)delegate + { + value.Package.UnloadUnusedAssets(); + AssetSystem.LogFormat(string.Intern("Free Asset Handle Release : {0}"), packageName); + }); } public override void UnloadUnusedAssets(bool isForce = false) { - foreach (var key in ReferenceOPHandle.Keys.ToArray()) - { - var temp = ReferenceOPHandle[key]; - if (temp.IsValid) continue; - var status = temp.Status; - if (status == EOperationStatus.Succeed || status == EOperationStatus.Processing) continue; - ReferenceOPHandle.Remove(key); - } - if (isForce) { ReferenceOPHandle.Clear(); - foreach (var value in Dic.Values) - value.Package.ForceUnloadAllAssets(); + Dic.Values.ToList().ForEach(value => value.Package.ForceUnloadAllAssets()); } else { + ReferenceOPHandle.Where(pair => !pair.Value.IsValid) + .Where(pair => pair.Value.Status != EOperationStatus.Succeed) + .Where(pair => pair.Value.Status != EOperationStatus.Processing) + .Select(pair => pair.Key) + .ToList() + .ForEach(item => ReferenceOPHandle.Remove(item)); Runner.StartCoroutine(UnloadUnusedAssetsCo(_ => { foreach (var value in Dic.Values) @@ -97,27 +90,25 @@ private static IEnumerator UnloadUnusedAssetsCo(Action completed private static void ReleaseOperationHandle(OperationHandleBase operation) { - if (operation.IsValid) - switch (operation) - { - case AllAssetsOperationHandle handle: - handle.Dispose(); - break; - case RawFileOperationHandle handle: - handle.Dispose(); - break; - case SubAssetsOperationHandle handle: - handle.Dispose(); - break; - case AssetOperationHandle handle: - handle.Dispose(); - break; - case SceneOperationHandle handle: - if (!handle.IsMainScene()) handle.UnloadAsync(); - break; - } - - operation = null; // 释放引用 + if (!operation.IsValid) return; + switch (operation) + { + case AllAssetsOperationHandle handle: + handle.Dispose(); + break; + case RawFileOperationHandle handle: + handle.Dispose(); + break; + case SubAssetsOperationHandle handle: + handle.Dispose(); + break; + case AssetOperationHandle handle: + handle.Dispose(); + break; + case SceneOperationHandle handle: + if (!handle.IsMainScene()) handle.UnloadAsync(); + break; + } } } } diff --git a/Extensions/YooAsset/Runtime/AssetOperationHandleExtension.cs b/Extensions/YooAsset/Runtime/AssetOperationHandleExtension.cs index 14dfd90..a70ce7b 100644 --- a/Extensions/YooAsset/Runtime/AssetOperationHandleExtension.cs +++ b/Extensions/YooAsset/Runtime/AssetOperationHandleExtension.cs @@ -1,35 +1,37 @@ -using UnityEngine; -using YooAsset; - -public static class AssetOperationHandleExtension -{ - /// - /// 获取资源对象 - /// - /// - /// - public static AssetOperationHandle GetAssetObject( - this AssetOperationHandle thisHandle, - out TAsset asset - ) where TAsset : Object - { - if (thisHandle.Status != EOperationStatus.Succeed) - { - var assetInfo = thisHandle.GetAssetInfo(); - Debug.LogWarning( - $"The {assetInfo.AssetPath}[{assetInfo.AssetType}] is not success. Error[{thisHandle.LastError}]"); - } - - asset = thisHandle.AssetObject as TAsset; - return thisHandle; - } - - /// - /// 等待异步执行完毕 - /// - public static AssetOperationHandle WaitForAsyncOperationComplete(this AssetOperationHandle thisHandle) - { - thisHandle.WaitForAsyncComplete(); - return thisHandle; - } -} \ No newline at end of file +// using UnityEngine; +// using YooAsset; +// +// public static class AssetOperationHandleExtension +// { +// /// +// /// 获取资源对象 +// /// +// /// +// /// +// /// +// public static AssetOperationHandle GetAssetObject( +// this AssetOperationHandle thisHandle, +// out TAsset asset +// ) +// where TAsset : Object +// { +// if (thisHandle.Status != EOperationStatus.Succeed) +// { +// var assetInfo = thisHandle.GetAssetInfo(); +// Debug.LogWarning( +// $"The {assetInfo.AssetPath}[{assetInfo.AssetType}] is not success. Error[{thisHandle.LastError}]"); +// } +// +// asset = thisHandle.AssetObject as TAsset; +// return thisHandle; +// } +// +// /// +// /// 等待异步执行完毕 +// /// +// public static AssetOperationHandle WaitForAsyncOperationComplete(this AssetOperationHandle thisHandle) +// { +// thisHandle.WaitForAsyncComplete(); +// return thisHandle; +// } +// } \ No newline at end of file diff --git a/Extensions/YooAsset/Runtime/LoadAssetsByTagOperation.cs b/Extensions/YooAsset/Runtime/LoadAssetsByTagOperation.cs index 45b6239..3a4c3bd 100644 --- a/Extensions/YooAsset/Runtime/LoadAssetsByTagOperation.cs +++ b/Extensions/YooAsset/Runtime/LoadAssetsByTagOperation.cs @@ -1,116 +1,111 @@ -using System.Collections.Generic; -using UnityEngine; -using YooAsset; - -public class LoadAssetsByTagOperation : GameAsyncOperation where TObject : Object -{ - private readonly string _tag; - private List _handles; - private ESteps _steps = ESteps.None; - - public LoadAssetsByTagOperation(string tag) - { - _tag = tag; - } - - /// - /// 资源对象集合 - /// - public List AssetObjects { private set; get; } - - protected override void OnStart() - { - _steps = ESteps.LoadAssets; - } - - protected override void OnUpdate() - { - if (_steps == ESteps.None || _steps == ESteps.Done) - return; - - if (_steps == ESteps.LoadAssets) - { - var assetInfos = YooAssets.GetAssetInfos(_tag); - _handles = new List(assetInfos.Length); - foreach (var assetInfo in assetInfos) - { - var handle = YooAssets.LoadAssetAsync(assetInfo); - _handles.Add(handle); - } - - _steps = ESteps.CheckResult; - } - - if (_steps == ESteps.CheckResult) - { - var index = 0; - foreach (var handle in _handles) - { - if (handle.IsDone == false) - { - Progress = (float)index / _handles.Count; - return; - } - - index++; - } - - AssetObjects = new List(_handles.Count); - foreach (var handle in _handles) - if (handle.Status == EOperationStatus.Succeed) - { - var assetObject = handle.AssetObject as TObject; - if (assetObject != null) - { - AssetObjects.Add(assetObject); - } - else - { - var error = $"资源类型转换失败:{handle.AssetObject.name}"; - Debug.LogError($"{error}"); - AssetObjects.Clear(); - SetFinish(false, error); - return; - } - } - else - { - Debug.LogError($"{handle.LastError}"); - AssetObjects.Clear(); - SetFinish(false, handle.LastError); - return; - } - - SetFinish(true); - } - } - - private void SetFinish(bool succeed, string error = "") - { - Error = error; - Status = succeed ? EOperationStatus.Succeed : EOperationStatus.Failed; - _steps = ESteps.Done; - } - - /// - /// 释放资源句柄 - /// - public void ReleaseHandle() - { - foreach (var handle in _handles) handle.Release(); - - _handles.Clear(); - } - - #region Nested type: ESteps - - private enum ESteps - { - None, - LoadAssets, - CheckResult, - Done - } - - #endregion -} \ No newline at end of file +// using System.Collections.Generic; +// using UnityEngine; +// using YooAsset; +// +// public class LoadAssetsByTagOperation : GameAsyncOperation +// where TObject : Object +// { +// private readonly string _tag; +// private List _handles; +// private ESteps _steps = ESteps.None; +// +// public LoadAssetsByTagOperation(string tag) { _tag = tag; } +// +// /// +// /// 资源对象集合 +// /// +// public List AssetObjects { private set; get; } +// +// protected override void OnStart() { _steps = ESteps.LoadAssets; } +// +// protected override void OnUpdate() +// { +// if (_steps == ESteps.None || _steps == ESteps.Done) +// return; +// +// if (_steps == ESteps.LoadAssets) +// { +// var assetInfos = YooAssets.GetAssetInfos(_tag); +// _handles = new List(assetInfos.Length); +// foreach (var assetInfo in assetInfos) +// { +// var handle = YooAssets.LoadAssetAsync(assetInfo); +// _handles.Add(handle); +// } +// +// _steps = ESteps.CheckResult; +// } +// +// if (_steps == ESteps.CheckResult) +// { +// var index = 0; +// foreach (var handle in _handles) +// { +// if (handle.IsDone == false) +// { +// Progress = (float)index / _handles.Count; +// return; +// } +// +// index++; +// } +// +// AssetObjects = new List(_handles.Count); +// foreach (var handle in _handles) +// if (handle.Status == EOperationStatus.Succeed) +// { +// var assetObject = handle.AssetObject as TObject; +// if (assetObject != null) +// { +// AssetObjects.Add(assetObject); +// } +// else +// { +// var error = $"资源类型转换失败:{handle.AssetObject.name}"; +// Debug.LogError($"{error}"); +// AssetObjects.Clear(); +// SetFinish(false, error); +// return; +// } +// } +// else +// { +// Debug.LogError($"{handle.LastError}"); +// AssetObjects.Clear(); +// SetFinish(false, handle.LastError); +// return; +// } +// +// SetFinish(true); +// } +// } +// +// private void SetFinish(bool succeed, string error = "") +// { +// Error = error; +// Status = succeed ? EOperationStatus.Succeed : EOperationStatus.Failed; +// _steps = ESteps.Done; +// } +// +// /// +// /// 释放资源句柄 +// /// +// public void ReleaseHandle() +// { +// foreach (var handle in _handles) handle.Release(); +// +// _handles.Clear(); +// } +// +// #region Nested type: ESteps +// +// private enum ESteps +// { +// None, +// LoadAssets, +// CheckResult, +// Done +// } +// +// #endregion +// } \ No newline at end of file diff --git a/Runtime/Basics/AssetSystem.Debug.cs b/Runtime/Basics/AssetSystem.Debug.cs index ebe7d02..5a663ac 100644 --- a/Runtime/Basics/AssetSystem.Debug.cs +++ b/Runtime/Basics/AssetSystem.Debug.cs @@ -39,7 +39,7 @@ partial class AssetSystem public static void LogWarningFormat(string format, params object[] args) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -54,7 +54,7 @@ public static void LogWarningFormat(string format, params object[] args) public static void LogWarning(string message) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -76,7 +76,7 @@ public static void LogWarning(string message) public static void LogException(Exception exception) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -98,7 +98,7 @@ public static void LogException(Exception exception) public static void LogException(string exception) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -117,7 +117,7 @@ public static void LogException(string exception) public static void LogExceptionFormat(string format, params object[] args) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -139,7 +139,7 @@ public static void LogExceptionFormat(string format, params object[] args) public static void Log(string message) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -158,7 +158,7 @@ public static void Log(string message) public static void LogFormat(string format, params object[] args) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -180,7 +180,7 @@ public static void LogFormat(string format, params object[] args) public static void LogError(string message) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif @@ -199,7 +199,7 @@ public static void LogError(string message) public static void LogErrorFormat(string format, params object[] args) { #if UNITY_EDITOR - if (Parameter is null || Parameter.OutputLog) + if (!Parameter || Parameter.OutputLog) #else if (Parameter.OutputLog) #endif diff --git a/Runtime/Basics/AssetSystem.cs b/Runtime/Basics/AssetSystem.cs index c66fb27..fcdc0f4 100644 --- a/Runtime/Basics/AssetSystem.cs +++ b/Runtime/Basics/AssetSystem.cs @@ -3,7 +3,6 @@ using System; using System.Collections; using System.Diagnostics; -using System.Linq; using System.Threading.Tasks; using AIO.UEngine; diff --git a/Runtime/Basics/Handle/LoaderHandle.cs b/Runtime/Basics/Handle/LoaderHandle.cs index d35741b..152c6d8 100644 --- a/Runtime/Basics/Handle/LoaderHandle.cs +++ b/Runtime/Basics/Handle/LoaderHandle.cs @@ -2,7 +2,6 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; - namespace AIO { [StructLayout(LayoutKind.Auto)] @@ -26,10 +25,11 @@ protected override void OnDispose() #region Constructor - protected LoaderHandle() { } + protected LoaderHandle() { AssetPath = string.Empty; } protected LoaderHandle(string location) { + AssetPath = string.Empty; if (string.IsNullOrEmpty(location)) { IsDone = true; @@ -64,10 +64,7 @@ protected LoaderHandle(string location, Type type, Action onCompleted) Completed += onCompleted; } - protected LoaderHandle(string location, Type type) : this(location) - { - AssetType = type; - } + protected LoaderHandle(string location, Type type) : this(location) { AssetType = type; } #endregion diff --git a/Runtime/Basics/Handle/LoaderHandleList.cs b/Runtime/Basics/Handle/LoaderHandleList.cs index 03e0c07..fa4c50f 100644 --- a/Runtime/Basics/Handle/LoaderHandleList.cs +++ b/Runtime/Basics/Handle/LoaderHandleList.cs @@ -15,7 +15,6 @@ internal abstract class LoaderHandleList public Type AssetType { get; protected set; } object IOperationList.this[int index] => Result[index]; - #region IOperationList event Action IOperationList.Completed @@ -32,13 +31,14 @@ event Action IOperationList.Completed #region Constructor - protected LoaderHandleList() { } + protected LoaderHandleList() { AssetPath = string.Empty; } protected LoaderHandleList(string location) { - Address = location; - IsDone = false; - Progress = 0; + AssetPath = string.Empty; + Address = location; + IsDone = false; + Progress = 0; } protected LoaderHandleList(string location, Action onCompleted) : this(location) @@ -53,10 +53,7 @@ protected LoaderHandleList(string location, Type type, Action onCompl Completed += onCompleted; } - protected LoaderHandleList(string location, Type type) : this(location) - { - AssetType = type; - } + protected LoaderHandleList(string location, Type type) : this(location) { AssetType = type; } #endregion } diff --git a/Runtime/Basics/HandleAction/DownloadTag.cs b/Runtime/Basics/HandleAction/DownloadTag.cs index 6479e85..2384ee9 100644 --- a/Runtime/Basics/HandleAction/DownloadTag.cs +++ b/Runtime/Basics/HandleAction/DownloadTag.cs @@ -1,4 +1,6 @@ -using System.Collections; +#region namespace + +using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -7,6 +9,8 @@ using System.Threading.Tasks; using AIO.UEngine; +#endregion + namespace AIO { [StructLayout(LayoutKind.Auto)] @@ -32,10 +36,7 @@ internal sealed class OperationDownloadTag : OperationAction /// private IASDownloader downloader; - protected override void OnDispose() - { - downloader = null; - } + protected override void OnDispose() { downloader = null; } protected override void CreateSync() { @@ -135,7 +136,7 @@ partial class AssetSystem /// 获取下载器 /// [DebuggerNonUserCode, DebuggerHidden] - public static IASDownloader GetDownloader(DownlandAssetEvent assetEvent = default) + public static IASDownloader GetDownloader(DownlandAssetEvent assetEvent = default(DownlandAssetEvent)) { return Parameter.ASMode != EASMode.Remote ? new ASDownloaderEmpty(assetEvent) @@ -191,18 +192,12 @@ public static IOperationAction DownloadRecord(DownlandAssetEvent assetEvent = de /// 预下载全部远端资源 /// [DebuggerNonUserCode, DebuggerHidden] - public static IOperationAction DownloadAll(DownlandAssetEvent assetEvent = default) - { - return new OperationDownloadTag(true, assetEvent); - } + public static IOperationAction DownloadAll(DownlandAssetEvent assetEvent = default) { return new OperationDownloadTag(true, assetEvent); } /// /// 动态下载远端资源 /// [DebuggerNonUserCode, DebuggerHidden] - public static IOperationAction DownloadHeader(DownlandAssetEvent assetEvent = default) - { - return new OperationDownloadTag(false, assetEvent); - } + public static IOperationAction DownloadHeader(DownlandAssetEvent assetEvent = default) { return new OperationDownloadTag(false, assetEvent); } } } \ No newline at end of file diff --git a/Runtime/Basics/HandleAction/InitializeTask.cs b/Runtime/Basics/HandleAction/InitializeTask.cs index 4b03386..939924e 100644 --- a/Runtime/Basics/HandleAction/InitializeTask.cs +++ b/Runtime/Basics/HandleAction/InitializeTask.cs @@ -132,7 +132,6 @@ protected override TaskAwaiter CreateAsync() return Awaiter; } - protected async Task OnAwaiter2() { await Proxy.UpdatePackagesTask(Config); @@ -170,10 +169,7 @@ protected override void OnCompleted() if (!IsValidate) throw new Exception("Initialize Error"); } - protected override void OnReset() - { - IsValidate = !AssetSystem.IsInitialized; - } + protected override void OnReset() { IsValidate = !AssetSystem.IsInitialized; } private T Proxy; private ASConfig Config; @@ -193,7 +189,7 @@ public OperationActionInitializeTask(T proxy, ASConfig config) return; } - if (config is null) + if (!config) { AssetSystem.ExceptionEvent(ASException.ASConfigIsNull); IsValidate = false; diff --git a/Runtime/Config/ASConfig.cs b/Runtime/Config/ASConfig.cs index 1702f58..8d035ae 100644 --- a/Runtime/Config/ASConfig.cs +++ b/Runtime/Config/ASConfig.cs @@ -1,22 +1,17 @@ -#region - -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; -using System.Linq; -using UnityEngine; - -#endregion - -#if UNITY_EDITOR +#if UNITY_EDITOR using UnityEditor; #endif namespace AIO.UEngine { - [Description("资源系统配置"), Serializable, - HelpURL("https://github.com/AIO-GAME/Unity.Asset.CLI/blob/main/.github/API_USAGE/Config.md#-aiouengineasconfig---%E8%B5%84%E6%BA%90%E7%B3%BB%E7%BB%9F%E9%85%8D%E7%BD%AE-")] + using System; + using System.ComponentModel; + using System.IO; + using System.Linq; + using UnityEngine; + + [Description("资源系统配置"), Serializable] + [HelpURL("https://github.com/AIO-GAME/Unity.Asset.CLI/blob/main/.github/API_USAGE/Config.md#-aiouengineasconfig---%E8%B5%84%E6%BA%90%E7%B3%BB%E7%BB%9F%E9%85%8D%E7%BD%AE-")] public class ASConfig : ScriptableObject { /// @@ -53,7 +48,7 @@ public class ASConfig : ScriptableObject /// /// 全局 可寻址路径全部包含扩展名 /// - public bool HasExtension = false; + public bool HasExtension; #endif /// @@ -164,7 +159,7 @@ public AssetSystem.SequenceRecordQueue SequenceRecord private static ASConfig instance; #endif - private static ASConfig GetResource() { return Resources.LoadAll(nameof(ASConfig)).FirstOrDefault(item => !(item is null)); } + private static ASConfig GetResource() { return Resources.LoadAll(nameof(ASConfig)).FirstOrDefault(item => item); } /// /// 获取本地资源包地址 @@ -174,14 +169,15 @@ public static ASConfig GetOrCreate() #if UNITY_EDITOR if (!instance) { - foreach (var item in AssetDatabase.FindAssets("t:ASConfig", new[] { "Assets" }) - .Select(AssetDatabase.GUIDToAssetPath) - .Select(AssetDatabase.LoadAssetAtPath)) - if (item) - { - instance = item; - break; - } + foreach (var item in AssetDatabase + .FindAssets("t:ASConfig", new[] { "Assets", }) + .Select(AssetDatabase.GUIDToAssetPath) + .Select(AssetDatabase.LoadAssetAtPath) + .Where(item => item)) + { + instance = item; + break; + } if (!instance) { @@ -261,7 +257,6 @@ public static ASConfig GetEditor(bool loadPathToLower = false) return config; } - [Conditional("UNITY_EDITOR")] public void Save() { if (Equals(null)) return; diff --git a/Runtime/Config/ASException.cs b/Runtime/Config/ASException.cs index 4d2dca8..10a732d 100644 --- a/Runtime/Config/ASException.cs +++ b/Runtime/Config/ASException.cs @@ -80,6 +80,6 @@ ASConfig 为空!请检查实现或输入实例! [Description(@" [EN:Configuration initialization failed] [CN:配置初始化失败]")] - SettingConfigInitializeFailure + SettingConfigInitializeFailure, } } \ No newline at end of file diff --git a/Runtime/Config/AssetsPackageConfig.cs b/Runtime/Config/AssetsPackageConfig.cs index 6f2b874..72e5de1 100644 --- a/Runtime/Config/AssetsPackageConfig.cs +++ b/Runtime/Config/AssetsPackageConfig.cs @@ -16,7 +16,7 @@ public enum ECompressMode LZMA, [InspectorName("LZ4")] - LZ4 + LZ4, } [Serializable] @@ -52,9 +52,6 @@ public class AssetsPackageConfig /// public bool IsLatest { get; set; } - public override string ToString() - { - return $"Name : {Name} , Version : {Version} , IsDefault : {IsDefault} , CompressMode : {CompressMode}"; - } + public override string ToString() { return $"Name : {Name} , Version : {Version} , IsDefault : {IsDefault} , CompressMode : {CompressMode}"; } } } \ No newline at end of file diff --git a/Runtime/Config/EASEventType.cs b/Runtime/Config/EASEventType.cs index 8a56229..21ceb45 100644 --- a/Runtime/Config/EASEventType.cs +++ b/Runtime/Config/EASEventType.cs @@ -69,6 +69,6 @@ public enum EASEventType /// 下载进度 /// [Description("下载进度")] - HotUpdateDownloadFinish + HotUpdateDownloadFinish, } } \ No newline at end of file diff --git a/Runtime/Config/EASMode.cs b/Runtime/Config/EASMode.cs index 5effe35..0e17ade 100644 --- a/Runtime/Config/EASMode.cs +++ b/Runtime/Config/EASMode.cs @@ -26,6 +26,6 @@ public enum EASMode /// 本地模式 /// [InspectorName("本地模式")] - Local + Local, } } \ No newline at end of file diff --git a/Runtime/Proxy.Empty/ASDownloaderEmpty.cs b/Runtime/Proxy.Empty/ASDownloaderEmpty.cs index d1ff610..49b98af 100644 --- a/Runtime/Proxy.Empty/ASDownloaderEmpty.cs +++ b/Runtime/Proxy.Empty/ASDownloaderEmpty.cs @@ -1,4 +1,4 @@ -#region +#region namespace using System; using System.Collections; @@ -10,24 +10,15 @@ namespace AIO { internal class ASDownloaderEmpty : AOperation, IASDownloader { - public ASDownloaderEmpty(DownlandAssetEvent dEvent) - { - Event = dEvent; - } + public ASDownloaderEmpty(DownlandAssetEvent dEvent) { Event = dEvent; } #region IASDownloader Members public bool Flow => false; - public void CollectNeedAll() - { - AssetSystem.WhiteAll = true; - } + public void CollectNeedAll() { AssetSystem.WhiteAll = true; } - public void CollectNeedTag(params string[] tags) - { - AssetSystem.AddWhite(AssetSystem.GetAddressByTag(tags)); - } + public void CollectNeedTag(params string[] tags) { AssetSystem.AddWhite(AssetSystem.GetAddressByTag(tags)); } Action IProgressEvent. OnBegin { get; set; } Action IProgressEvent. OnError { get; set; } @@ -44,10 +35,7 @@ public void CollectNeedTag(params string[] tags) #endregion - protected override void OnWait() - { - Event.OnComplete?.Invoke(Report); - } + protected override void OnWait() { Event.OnComplete?.Invoke(Report); } protected override Task OnWaitAsync() { diff --git a/Runtime/Proxy/ASProxy.Info.cs b/Runtime/Proxy/ASProxy.Info.cs index 99bfc21..9b8950b 100644 --- a/Runtime/Proxy/ASProxy.Info.cs +++ b/Runtime/Proxy/ASProxy.Info.cs @@ -13,7 +13,7 @@ partial class ASProxy /// 获取下载器 /// /// - public abstract IASDownloader GetDownloader(DownlandAssetEvent progress = default); + public abstract IASDownloader GetDownloader(DownlandAssetEvent progress = default(DownlandAssetEvent)); #region 资源信息 diff --git a/Runtime/Proxy/ASProxy.Loader.cs b/Runtime/Proxy/ASProxy.Loader.cs index d872e45..f3beb91 100644 --- a/Runtime/Proxy/ASProxy.Loader.cs +++ b/Runtime/Proxy/ASProxy.Loader.cs @@ -1,4 +1,4 @@ -#region +#region namespace using System; using UnityEngine; diff --git a/Runtime/Proxy/ASProxy.PreLoad.cs b/Runtime/Proxy/ASProxy.PreLoad.cs index 1c51fe3..a16bed4 100644 --- a/Runtime/Proxy/ASProxy.PreLoad.cs +++ b/Runtime/Proxy/ASProxy.PreLoad.cs @@ -1,4 +1,4 @@ -#region +#region namespace using System; using System.Threading.Tasks; diff --git a/Runtime/Proxy/ASProxy.UnLoad.cs b/Runtime/Proxy/ASProxy.UnLoad.cs index 3c85ec4..5e5ea02 100644 --- a/Runtime/Proxy/ASProxy.UnLoad.cs +++ b/Runtime/Proxy/ASProxy.UnLoad.cs @@ -37,7 +37,7 @@ public virtual void HandleFree(IEnumerable locations) [DebuggerNonUserCode, DebuggerHidden] public virtual void HandleFree(IList locations) { - for (var index = 0; index < locations.Count; index++) HandleFree(locations[index]); + foreach (var location in locations) HandleFree(location); } ///