From e955715c99c474881e0b27ecc325061ce0d866a0 Mon Sep 17 00:00:00 2001 From: quyong Date: Wed, 8 Apr 2026 11:47:57 +0800 Subject: [PATCH] feat: add option to remove from preloadedAssets when build player close #393 --- .../Editor/UIEffectProjectSettingsEditor.cs | 21 +++++ Packages/src/README.md | 15 ++++ .../PreloadedProjectSettings.cs | 56 ++++++++++-- .../Runtime/Internal/Utilities/Logger.cs.meta | 11 ++- .../Utilities/ShaderVariantRegistry.cs | 90 +++++++++++++++++-- .../src/Runtime/UIEffectProjectSettings.cs | 9 ++ 6 files changed, 187 insertions(+), 15 deletions(-) diff --git a/Packages/src/Editor/UIEffectProjectSettingsEditor.cs b/Packages/src/Editor/UIEffectProjectSettingsEditor.cs index 03c056e..aa7b3f8 100644 --- a/Packages/src/Editor/UIEffectProjectSettingsEditor.cs +++ b/Packages/src/Editor/UIEffectProjectSettingsEditor.cs @@ -16,6 +16,7 @@ namespace Coffee.UIEffects.Editors private SerializedProperty _runtimePresets; private SerializedProperty _runtimePresetsV2; private SerializedProperty _useHDRColorPicker; + private SerializedProperty _preLoadSettingsInBuild; private bool _isInitialized; private ShaderVariantRegistryEditor _shaderVariantRegistryEditor; private UIEffect[] _legacyPresets; @@ -29,6 +30,7 @@ namespace Coffee.UIEffects.Editors _useHDRColorPicker = serializedObject.FindProperty("m_UseHDRColorPicker"); _runtimePresets = serializedObject.FindProperty("m_RuntimePresets"); _runtimePresetsV2 = serializedObject.FindProperty("m_RuntimePresetsV2"); + _preLoadSettingsInBuild = serializedObject.FindProperty("m_PreLoadSettingsInBuild"); _reorderableList = new ReorderableList(serializedObject, _runtimePresetsV2, true, true, true, true); _reorderableList.drawHeaderCallback = rect => EditorGUI.LabelField(rect, "Runtime Presets"); @@ -77,6 +79,7 @@ namespace Coffee.UIEffects.Editors // Editor // Use HDR color pickers. + EditorGUIUtility.labelWidth = 200; EditorGUILayout.PropertyField(_useHDRColorPicker); // Shader @@ -95,6 +98,24 @@ namespace Coffee.UIEffects.Editors } _shaderVariantRegistryEditor.Draw(); + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Advanced", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(_preLoadSettingsInBuild); + if (!_preLoadSettingsInBuild.boolValue) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.HelpBox("UIEffectProjectSettings asset will not be built in." + + "please load manually from Resources, AssetBundle, or Addressables before using UIEffect.", + MessageType.Warning); + if (GUILayout.Button("Ping")) + { + EditorGUIUtility.PingObject(target); + } + + EditorGUILayout.EndHorizontal(); + } + GUILayout.FlexibleSpace(); serializedObject.ApplyModifiedProperties(); } diff --git a/Packages/src/README.md b/Packages/src/README.md index e1459b4..4c98472 100644 --- a/Packages/src/README.md +++ b/Packages/src/README.md @@ -631,6 +631,21 @@ You can adjust the project-wide settings for UIEffect. (`Edit > Project Settings > - The setting file is usually saved in `Assets/ProjectSettings/UIEffectProjectSettings.asset`. Include this file in your version control system. > - The setting file is automatically added as a preloaded asset in `ProjectSettings/ProjectSettings.asset`. +#### Advanced + +- **Pre Load Settings In Build**: When enabled, this settings asset will be added to `PlayerSettings.preloadedAssets` in build. + - When disable, you should load this settings via `Resources`, `AssetBundles` or `Addressables` to use `UIEffect`. + - You can overwrite the settings by re-enabling `UIEffectProjectSettings`. This allows you to hot update shader variants and presets. + +```csharp +private static IEnumerator HotUpdateCoroutine() +{ + const string k_SettingsAddress = "Assets/ProjectSettings/UIEffectProjectSettings.asset"; + yield return Addressables.LoadAssetAsync(k_SettingsAddress); + while (UIEffectProjectSettings.shaderVariantCollection.WarmUpProgressively(5) == false) yield return null; +} +``` +

### :warning: Limitations diff --git a/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs b/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs index 94b2fe9..7d1188e 100644 --- a/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs +++ b/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs @@ -14,6 +14,14 @@ namespace Coffee.UIEffectInternal public abstract class PreloadedProjectSettings : ScriptableObject #if UNITY_EDITOR { + [Tooltip("When enabled, this settings asset will be added to PlayerSettings.preloadedAssets in build.\n\n" + + "When disable, you should load this settings via Resources, AssetBundles or " + + "Addressables to use UIEffect.")] + [SerializeField] + private bool m_PreLoadSettingsInBuild = true; + + protected static bool s_BuildingPlayer; + private class Postprocessor : AssetPostprocessor { private static void OnPostprocessAllAssets(string[] _, string[] __, string[] ___, string[] ____) @@ -22,14 +30,47 @@ namespace Coffee.UIEffectInternal } } - private class PreprocessBuildWithReport : IPreprocessBuildWithReport + private class ExcludeFromBuild : IPreprocessBuildWithReport, IPostprocessBuildWithReport { int IOrderedCallback.callbackOrder => 0; void IPreprocessBuildWithReport.OnPreprocessBuild(BuildReport report) { + s_BuildingPlayer = true; + + foreach (var t in TypeCache.GetTypesDerivedFrom(typeof(PreloadedProjectSettings<>))) + { + var settings = GetDefaultSettings(t); + if (!settings || settings.m_PreLoadSettingsInBuild) continue; + + PlayerSettings.SetPreloadedAssets( + PlayerSettings.GetPreloadedAssets() + .Where(x => x && x.GetType() != t) + .ToArray()); + + Debug.Log($"[PreloadedProjectSettings] Build started: removed '{settings.name}' " + + $"({t.Name}) from PreloadedAssets. " + + $"It will be restored after build completes."); + } + Initialize(); } + + void IPostprocessBuildWithReport.OnPostprocessBuild(BuildReport report) + { + s_BuildingPlayer = false; + + Initialize(); + + foreach (var t in TypeCache.GetTypesDerivedFrom(typeof(PreloadedProjectSettings<>))) + { + var settings = GetDefaultSettings(t); + if (!settings || settings.m_PreLoadSettingsInBuild) continue; + + Debug.Log($"[PreloadedProjectSettings] Build finished: restored '{settings.name}' " + + $"({t.Name}) to PreloadedAssets."); + } + } } private static void Initialize() @@ -41,11 +82,11 @@ namespace Coffee.UIEffectInternal { // When create a new instance, automatically set it as default settings. defaultSettings = CreateInstance(t) as PreloadedProjectSettings; - SetDefaultSettings(defaultSettings); + if (!s_BuildingPlayer) SetDefaultSettings(defaultSettings); } else if (GetPreloadedSettings(t).Length != 1) { - SetDefaultSettings(defaultSettings); + if (!s_BuildingPlayer) SetDefaultSettings(defaultSettings); } if (defaultSettings != null) @@ -151,7 +192,7 @@ namespace Coffee.UIEffectInternal return s_Instance; } - SetDefaultSettings(s_Instance); + if (!s_BuildingPlayer) SetDefaultSettings(s_Instance); return s_Instance; } } @@ -193,9 +234,12 @@ namespace Coffee.UIEffectInternal } EditorApplication.playModeStateChanged += OnPlayModeStateChanged; +#else + if (s_Instance && s_Instance != this) + { + Destroy(s_Instance); + } #endif - - if (s_Instance != null) return; s_Instance = this as T; } diff --git a/Packages/src/Runtime/Internal/Utilities/Logger.cs.meta b/Packages/src/Runtime/Internal/Utilities/Logger.cs.meta index 6d91ea0..6c1d4b5 100644 --- a/Packages/src/Runtime/Internal/Utilities/Logger.cs.meta +++ b/Packages/src/Runtime/Internal/Utilities/Logger.cs.meta @@ -1,2 +1,11 @@ fileFormatVersion: 2 -guid: a2fa34e76bcd14489a1af18b393c3e65 \ No newline at end of file +guid: a2fa34e76bcd14489a1af18b393c3e65 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs b/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs index 0253238..87dd520 100644 --- a/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs +++ b/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs @@ -45,6 +45,7 @@ namespace Coffee.UIEffectInternal } private Dictionary _cachedOptionalShaders = new Dictionary(); + private Dictionary _shaderByName; [SerializeField] private List m_OptionalShaders = new List(); @@ -52,6 +53,9 @@ namespace Coffee.UIEffectInternal [SerializeField] internal ShaderVariantCollection m_Asset; + [SerializeField] + private List m_RegisteredShaders = new List(); + #if UNITY_EDITOR [SerializeField] private bool m_ErrorOnUnregisteredVariant = false; @@ -63,6 +67,52 @@ namespace Coffee.UIEffectInternal public ShaderVariantCollection shaderVariantCollection => m_Asset; public Func onShaderRequested; + /// + /// Build the runtime name-to-shader lookup from . + /// When shaders are delivered via AssetBundles (i.e. not in the player build), + /// cannot locate them by name. This lookup provides + /// direct references serialized at edit-time as a reliable alternative. + /// + public void InitializeShaderLookup() + { + var count = m_RegisteredShaders.Count; + if (count == 0) return; + + if (_shaderByName == null) + { + _shaderByName = new Dictionary(count); + } + else + { + _shaderByName.Clear(); + } + + for (var i = 0; i < count; i++) + { + var s = m_RegisteredShaders[i]; + if (s) + { + _shaderByName[s.name] = s; + } + } + } + + /// + /// Find a shader by name. Prefers the registered direct reference from + /// when available, falls back to + /// otherwise. This ensures correct behavior in both + /// built-in delivery (PreloadedAssets) and external delivery (AssetBundle) modes. + /// + public Shader FindShaderByName(string name) + { + if (_shaderByName != null && _shaderByName.TryGetValue(name, out var shader) && shader) + { + return shader; + } + + return Shader.Find(name); + } + public Shader FindOptionalShader(Shader shader, string requiredName, string format, @@ -74,7 +124,7 @@ namespace Coffee.UIEffectInternal var id = shader.GetHashCode(); if (_cachedOptionalShaders.TryGetValue(id, out var optionalShaderName)) { - return Shader.Find(optionalShaderName); + return FindShaderByName(optionalShaderName); } // The shader has required name. @@ -92,7 +142,7 @@ namespace Coffee.UIEffectInternal { var pair = m_OptionalShaders[i]; if (pair.key != shaderName) continue; - optionalShader = Shader.Find(pair.value); + optionalShader = FindShaderByName(pair.value); if (!optionalShader) continue; _cachedOptionalShaders[id] = pair.value; return optionalShader; @@ -100,7 +150,7 @@ namespace Coffee.UIEffectInternal // Find optional shader by format. optionalShaderName = string.Format(format, shaderName); - optionalShader = Shader.Find(optionalShaderName); + optionalShader = FindShaderByName(optionalShaderName); if (optionalShader) { _cachedOptionalShaders[id] = optionalShaderName; @@ -110,13 +160,13 @@ namespace Coffee.UIEffectInternal #if UNITY_EDITOR if (onShaderRequested?.Invoke(optionalShaderName) ?? false) { - return Shader.Find(defaultOptionalShaderName); + return FindShaderByName(defaultOptionalShaderName); } #endif // Find default optional shader. _cachedOptionalShaders[id] = defaultOptionalShaderName; - return Shader.Find(defaultOptionalShaderName); + return FindShaderByName(defaultOptionalShaderName); } #if UNITY_EDITOR @@ -208,10 +258,37 @@ namespace Coffee.UIEffectInternal AssetDatabase.SaveAssets(); } + SyncRegisteredShaders(owner); ClearCache(); Profiler.EndSample(); } + /// + /// Sync based on the current delivery mode. + /// When is enabled, + /// extracts shader references from the SVC so they can be resolved at runtime + /// without . Otherwise clears the list to avoid + /// stale references and unnecessary asset dependencies. + /// + private void SyncRegisteredShaders(Object owner) + { + var so = new SerializedObject(m_Asset); + var shaders = so.FindProperty("m_Shaders"); + m_RegisteredShaders.Clear(); + for (var i = 0; i < shaders.arraySize; i++) + { + var shaderRef = shaders.GetArrayElementAtIndex(i) + .FindPropertyRelative("first") + .objectReferenceValue as Shader; + if (shaderRef && !m_RegisteredShaders.Contains(shaderRef)) + { + m_RegisteredShaders.Add(shaderRef); + } + } + + EditorUtility.SetDirty(owner); + } + internal void RegisterVariant(Material material, string path) { if (!material || !material.shader || !m_Asset) return; @@ -429,10 +506,7 @@ namespace Coffee.UIEffectInternal EditorGUILayout.Space(-20); } - var labelWidth = EditorGUIUtility.labelWidth; - EditorGUIUtility.labelWidth = 180; EditorGUILayout.PropertyField(_errorOnUnregisteredVariant); - EditorGUIUtility.labelWidth = labelWidth; } private static void AddVariant(ShaderVariantCollection collection, string shaderName, string keywords) diff --git a/Packages/src/Runtime/UIEffectProjectSettings.cs b/Packages/src/Runtime/UIEffectProjectSettings.cs index baa564f..4ea4fb9 100644 --- a/Packages/src/Runtime/UIEffectProjectSettings.cs +++ b/Packages/src/Runtime/UIEffectProjectSettings.cs @@ -83,6 +83,14 @@ namespace Coffee.UIEffects #pragma warning restore CS0618 } +#if !UNITY_EDITOR + protected override void OnEnable() + { + base.OnEnable(); + m_ShaderVariantRegistry.InitializeShaderLookup(); + } +#endif + #if UNITY_EDITOR private const string k_PresetDir = "UIEffectPresets"; private const string k_PresetSaveDir = "Assets/ProjectSettings/" + k_PresetDir; @@ -214,6 +222,7 @@ namespace Coffee.UIEffects base.OnEnable(); m_ShaderVariantRegistry.onShaderRequested = ShaderSampleImporter.ImportShaderIfSelected; m_ShaderVariantRegistry.ClearCache(); + m_ShaderVariantRegistry.InitializeShaderLookup(); } protected override void OnCreateAsset()