From 6e8aaf36f00e4a42f7b9d6f79e065d4022b567c2 Mon Sep 17 00:00:00 2001 From: mob-sakai <12690315+mob-sakai@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:10:18 +0900 Subject: [PATCH] fix: fix potential NPE in code --- .../Extensions/ComponentExtensions.cs | 7 ++++ .../PreloadedProjectSettings.cs | 6 +++ .../Runtime/Internal/Utilities/FastAction.cs | 2 + .../Runtime/Internal/Utilities/FrameCache.cs | 16 ++++++++ .../Internal/Utilities/MaterialRepository.cs | 4 ++ .../src/Runtime/Internal/Utilities/Misc.cs | 10 ++++- .../Internal/Utilities/ObjectRepository.cs | 13 ++++-- .../Utilities/ShaderSampleImporter.cs | 11 +++-- .../Utilities/ShaderVariantRegistry.cs | 40 ++++++++++++++++--- .../Internal/Utilities/UIExtraCallbacks.cs | 13 ++++-- Packages/src/Runtime/UIEffect.cs | 1 + 11 files changed, 106 insertions(+), 17 deletions(-) diff --git a/Packages/src/Runtime/Internal/Extensions/ComponentExtensions.cs b/Packages/src/Runtime/Internal/Extensions/ComponentExtensions.cs index fc642bf..c32054a 100644 --- a/Packages/src/Runtime/Internal/Extensions/ComponentExtensions.cs +++ b/Packages/src/Runtime/Internal/Extensions/ComponentExtensions.cs @@ -58,7 +58,10 @@ namespace Coffee.UIEffectInternal public static void GetComponentsInChildren(this Component self, List results, int depth) where T : Component { + if (results == null) return; + results.Clear(); + if (self == null) return; self.GetComponentsInChildren_Internal(results, depth); } @@ -97,6 +100,8 @@ namespace Coffee.UIEffectInternal /// public static T GetRootComponent(this Component self) where T : Component { + if (self == null) return null; + T component = null; var transform = self.transform; while (transform != null) @@ -119,6 +124,8 @@ namespace Coffee.UIEffectInternal Predicate valid) where T : Component { + if (self == null || valid == null) return null; + var tr = includeSelf ? self.transform : self.transform.parent; while (tr != null) { diff --git a/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs b/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs index 8639c07..71594d5 100644 --- a/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs +++ b/Packages/src/Runtime/Internal/ProjectSettings/PreloadedProjectSettings.cs @@ -164,6 +164,8 @@ namespace Coffee.UIEffectInternal protected void DrawPreLoadSettingsInBuild(string packageName) { + if (_preLoadSettingsInBuild == null) return; + EditorGUILayout.PropertyField(_preLoadSettingsInBuild); if (!_preLoadSettingsInBuild.boolValue) { @@ -298,9 +300,13 @@ namespace Coffee.UIEffectInternal } _target = instance; + if (_target == null) return; + _editor = Editor.CreateEditor(_target); } + if (_editor == null) return; + _editor.OnInspectorGUI(); } } diff --git a/Packages/src/Runtime/Internal/Utilities/FastAction.cs b/Packages/src/Runtime/Internal/Utilities/FastAction.cs index 907c7fb..6f28ecf 100755 --- a/Packages/src/Runtime/Internal/Utilities/FastAction.cs +++ b/Packages/src/Runtime/Internal/Utilities/FastAction.cs @@ -51,6 +51,8 @@ namespace Coffee.UIEffectInternal /// protected void Invoke(Action callback) { + if (callback == null) return; + var node = _delegates.First; while (node != null) { diff --git a/Packages/src/Runtime/Internal/Utilities/FrameCache.cs b/Packages/src/Runtime/Internal/Utilities/FrameCache.cs index e0b84ae..4eead7c 100644 --- a/Packages/src/Runtime/Internal/Utilities/FrameCache.cs +++ b/Packages/src/Runtime/Internal/Utilities/FrameCache.cs @@ -29,6 +29,12 @@ namespace Coffee.UIEffectInternal /// public static bool TryGet(object key1, string key2, out T result) { + if (key1 == null || key2 == null) + { + result = default; + return false; + } + return GetFrameCache().TryGet((key1.GetHashCode(), key2.GetHashCode()), out result); } @@ -37,6 +43,12 @@ namespace Coffee.UIEffectInternal /// public static bool TryGet(object key1, string key2, int key3, out T result) { + if (key1 == null || key2 == null) + { + result = default; + return false; + } + return GetFrameCache().TryGet((key1.GetHashCode(), key2.GetHashCode() + key3), out result); } @@ -45,6 +57,8 @@ namespace Coffee.UIEffectInternal /// public static void Set(object key1, string key2, T result) { + if (key1 == null || key2 == null) return; + GetFrameCache().Set((key1.GetHashCode(), key2.GetHashCode()), result); } @@ -53,6 +67,8 @@ namespace Coffee.UIEffectInternal /// public static void Set(object key1, string key2, int key3, T result) { + if (key1 == null || key2 == null) return; + GetFrameCache().Set((key1.GetHashCode(), key2.GetHashCode() + key3), result); } diff --git a/Packages/src/Runtime/Internal/Utilities/MaterialRepository.cs b/Packages/src/Runtime/Internal/Utilities/MaterialRepository.cs index 7692aec..1a30dd3 100644 --- a/Packages/src/Runtime/Internal/Utilities/MaterialRepository.cs +++ b/Packages/src/Runtime/Internal/Utilities/MaterialRepository.cs @@ -49,6 +49,8 @@ namespace Coffee.UIEffectInternal /// public static void Get(Hash128 hash, ref Material material, string shaderName) { + if (onShaderFind == null) return; + Profiler.BeginSample("(COF)[MaterialRepository] Get"); s_Repository.Get(hash, ref material, x => new Material(onShaderFind(x)) { @@ -62,6 +64,8 @@ namespace Coffee.UIEffectInternal /// public static void Get(Hash128 hash, ref Material material, string shaderName, string[] keywords) { + if (onShaderFind == null) return; + Profiler.BeginSample("(COF)[MaterialRepository] Get"); s_Repository.Get(hash, ref material, x => new Material(onShaderFind(x.shaderName)) { diff --git a/Packages/src/Runtime/Internal/Utilities/Misc.cs b/Packages/src/Runtime/Internal/Utilities/Misc.cs index 4c24df1..b281a9c 100644 --- a/Packages/src/Runtime/Internal/Utilities/Misc.cs +++ b/Packages/src/Runtime/Internal/Utilities/Misc.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; +using Debug = UnityEngine.Debug; #if UNITY_EDITOR using System.IO; using System.Linq; @@ -67,7 +68,7 @@ namespace Coffee.UIEffectInternal public static T[] GetAllComponentsInPrefabStage() where T : Component { var prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); - if (prefabStage == null) return Array.Empty(); + if (prefabStage == null || prefabStage.prefabContentsRoot == null) return Array.Empty(); return prefabStage.prefabContentsRoot.GetComponentsInChildren(true); } @@ -102,12 +103,17 @@ namespace Coffee.UIEffectInternal #if UNITY_EDITOR private static Action s_SetIconForObject = typeof(EditorGUIUtility) .GetMethod("SetIconForObject", BindingFlags.Static | BindingFlags.NonPublic) - .CreateDelegate(typeof(Action), null) as Action; + ?.CreateDelegate(typeof(Action), null) as Action; [InitializeOnLoadMethod] private static void InitializeOnLoadMethod() { if (Misc.isBatchOrBuilding) return; + if (s_SetIconForObject == null) + { + Debug.LogError("Could not retrieve the object icon API."); + return; + } var types = TypeCache.GetTypesWithAttribute(typeof(IconAttribute)); var scripts = MonoImporter.GetAllRuntimeMonoScripts(); diff --git a/Packages/src/Runtime/Internal/Utilities/ObjectRepository.cs b/Packages/src/Runtime/Internal/Utilities/ObjectRepository.cs index cd6ee57..cd6d2c7 100644 --- a/Packages/src/Runtime/Internal/Utilities/ObjectRepository.cs +++ b/Packages/src/Runtime/Internal/Utilities/ObjectRepository.cs @@ -71,6 +71,8 @@ namespace Coffee.UIEffectInternal /// public void Get(Hash128 hash, ref T obj, Func onCreate) { + if (onCreate == null) return; + if (GetFromCache(hash, ref obj)) return; Add(hash, ref obj, onCreate()); } @@ -80,6 +82,8 @@ namespace Coffee.UIEffectInternal /// public void Get(Hash128 hash, ref T obj, Func onCreate, TS source) { + if (onCreate == null) return; + if (GetFromCache(hash, ref obj)) return; Add(hash, ref obj, onCreate(source)); } @@ -92,7 +96,7 @@ namespace Coffee.UIEffectInternal { if (entry.storedObject == null) { - Release(ref entry.storedObject); + Remove(entry); Profiler.EndSample(); return false; } @@ -127,10 +131,11 @@ namespace Coffee.UIEffectInternal Profiler.BeginSample("(COF)[ObjectRepository] Add"); var newEntry = 0 < _pool.Count ? _pool.Pop() : new Entry(); newEntry.storedObject = newObject; + newEntry.objectId = newObject.GetHashCode(); newEntry.hash = hash; newEntry.reference = 1; _cache[hash] = newEntry; - _objectKey[newObject.GetHashCode()] = hash; + _objectKey[newEntry.objectId] = hash; Logger.Log(_name, $"Add(total#{count}): {newEntry}"); Release(ref obj); obj = newObject; @@ -175,7 +180,7 @@ namespace Coffee.UIEffectInternal Profiler.BeginSample("(COF)[ObjectRepository] Remove"); _cache.Remove(entry.hash); - _objectKey.Remove(entry.storedObject.GetHashCode()); + _objectKey.Remove(entry.objectId); _pool.Push(entry); entry.reference = 0; Logger.Log(_name, $"Remove(total#{_cache.Count}): {entry}"); @@ -186,12 +191,14 @@ namespace Coffee.UIEffectInternal private class Entry { public Hash128 hash; + public int objectId; public int reference; public T storedObject; public void Release(Action onRelease) { reference = 0; + objectId = 0; if (storedObject != null) { onRelease?.Invoke(storedObject); diff --git a/Packages/src/Runtime/Internal/Utilities/ShaderSampleImporter.cs b/Packages/src/Runtime/Internal/Utilities/ShaderSampleImporter.cs index 84f74fe..d5ae5ca 100644 --- a/Packages/src/Runtime/Internal/Utilities/ShaderSampleImporter.cs +++ b/Packages/src/Runtime/Internal/Utilities/ShaderSampleImporter.cs @@ -24,7 +24,7 @@ namespace Coffee.UIEffectInternal public static void RegisterShaderSamples((string shaderName, string sampleName, string version)[] samples) { - if (IsBatchOrBuilding()) return; + if (samples == null || IsBatchOrBuilding()) return; // Collect sample names. s_Samples = samples; @@ -37,6 +37,8 @@ namespace Coffee.UIEffectInternal public static void RegisterShaderAliases((string, string)[] aliases) { + if (aliases == null) return; + foreach (var (from, to) in aliases) { s_ShaderAliases[from] = to; @@ -57,7 +59,7 @@ namespace Coffee.UIEffectInternal /// public static bool ImportShaderIfSelected(string shaderName) { - if (IsBatchOrBuilding()) return false; + if (string.IsNullOrEmpty(shaderName) || IsBatchOrBuilding()) return false; if (s_ShaderAliases.TryGetValue(shaderName, out var alias)) { @@ -72,6 +74,7 @@ namespace Coffee.UIEffectInternal { message += "\n\nFor details, please see the readme."; } + return ImportSampleIfSelected(sampleName, message); } @@ -104,6 +107,7 @@ namespace Coffee.UIEffectInternal Application.OpenURL(s_ReadmeUrl); return false; } + if (selected != 0) return false; } else if (!EditorUtility.DisplayDialog($"Import {sampleName}", message, "Import", "Cancel")) @@ -135,7 +139,8 @@ namespace Coffee.UIEffectInternal var path = AssetDatabase.GetAssetPath(shader); if (string.IsNullOrEmpty(path)) return null; - return AssetImporter.GetAtPath(path).userData; + var importer = AssetImporter.GetAtPath(path); + return importer != null ? importer.userData : null; } private static void DeleteShader(string shaderName) diff --git a/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs b/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs index 862514b..4e833fe 100644 --- a/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs +++ b/Packages/src/Runtime/Internal/Utilities/ShaderVariantRegistry.cs @@ -75,18 +75,18 @@ namespace Coffee.UIEffectInternal /// public void InitializeShaderLookup() { - var count = m_RegisteredShaders.Count; - if (count == 0) return; - if (_shaderByName == null) { - _shaderByName = new Dictionary(count); + _shaderByName = new Dictionary(); } else { _shaderByName.Clear(); } + if (m_RegisteredShaders == null) return; + + var count = m_RegisteredShaders.Count; for (var i = 0; i < count; i++) { var s = m_RegisteredShaders[i]; @@ -105,6 +105,8 @@ namespace Coffee.UIEffectInternal /// public Shader FindShaderByName(string name) { + if (string.IsNullOrEmpty(name)) return null; + if (_shaderByName != null && _shaderByName.TryGetValue(name, out var shader) && shader != null) { return shader; @@ -120,6 +122,16 @@ namespace Coffee.UIEffectInternal { if (shader == null) return null; + if (_cachedOptionalShaders == null) + { + _cachedOptionalShaders = new Dictionary(); + } + + if (m_OptionalShaders == null) + { + m_OptionalShaders = new List(); + } + // Already cached. var id = shader.GetHashCode(); if (_cachedOptionalShaders.TryGetValue(id, out var optionalShaderName)) @@ -141,6 +153,8 @@ namespace Coffee.UIEffectInternal for (var i = 0; i < count; i++) { var pair = m_OptionalShaders[i]; + if (pair == null) continue; + if (pair.key != shaderName) continue; optionalShader = FindShaderByName(pair.value); if (optionalShader == null) continue; @@ -178,7 +192,15 @@ namespace Coffee.UIEffectInternal public void ClearCache() { - _cachedOptionalShaders.Clear(); + if (_cachedOptionalShaders == null) + { + _cachedOptionalShaders = new Dictionary(); + } + else + { + _cachedOptionalShaders.Clear(); + } + _cachedVariants.Clear(); } @@ -213,7 +235,10 @@ namespace Coffee.UIEffectInternal // Register optional shader names by shader comment. var pattern = $"// \\[OptionalShader\\] {packageName}: (.*)$"; - var registeredKeys = new HashSet(m_OptionalShaders.Select(x => x.key)); + m_OptionalShaders = m_OptionalShaders ?? new List(); + var registeredKeys = new HashSet(m_OptionalShaders + .Where(x => x != null) + .Select(x => x.key)); var keys = File.ReadLines(path) .Take(10) .Select(line => Regex.Match(line, pattern)) @@ -279,6 +304,7 @@ namespace Coffee.UIEffectInternal if (m_Asset == null) return; var so = new SerializedObject(m_Asset); var shaders = so.FindProperty("m_Shaders"); + if (shaders == null) return; // Get all shaders in the SVC, ignoring nulls and duplicates. var shadersInSVC = Enumerable.Range(0, shaders.arraySize) @@ -290,6 +316,7 @@ namespace Coffee.UIEffectInternal // ShaderVariantCollection entry order is not stable between editor sessions. // The registry is a lookup set, so an order-only difference is already in sync. + m_RegisteredShaders = m_RegisteredShaders ?? new List(); if (m_RegisteredShaders.Count == shadersInSVC.Count && new HashSet(m_RegisteredShaders).SetEquals(shadersInSVC)) { @@ -304,6 +331,7 @@ namespace Coffee.UIEffectInternal internal void RegisterVariant(Material material, string path) { if (material == null || material.shader == null || m_Asset == null) return; + m_UnregisteredVariants = m_UnregisteredVariants ?? new List(); Profiler.BeginSample("(EDITOR/COF)[ShaderVariantRegistry] RegisterVariant"); var (variant, pair) = GetVariant(material); diff --git a/Packages/src/Runtime/Internal/Utilities/UIExtraCallbacks.cs b/Packages/src/Runtime/Internal/Utilities/UIExtraCallbacks.cs index 660f286..3e4bf95 100755 --- a/Packages/src/Runtime/Internal/Utilities/UIExtraCallbacks.cs +++ b/Packages/src/Runtime/Internal/Utilities/UIExtraCallbacks.cs @@ -66,9 +66,16 @@ namespace Coffee.UIEffectInternal CanvasUpdateRegistry.IsRebuildingLayout(); #if TMP_ENABLE // Explicitly set `Canvas.willRenderCanvases += TMP_UpdateManager.DoRebuilds`. - var _ = typeof(TMPro.TMP_UpdateManager) - .GetProperty("instance", BindingFlags.NonPublic | BindingFlags.Static) - .GetValue(null); + var property = typeof(TMPro.TMP_UpdateManager) + .GetProperty("instance", BindingFlags.NonPublic | BindingFlags.Static); + if (property == null) + { + Debug.LogError("Could not retrieve the TextMeshPro update manager."); + } + else + { + var _ = property.GetValue(null); + } #endif Canvas.willRenderCanvases -= OnAfterCanvasRebuild; Canvas.willRenderCanvases += OnAfterCanvasRebuild; diff --git a/Packages/src/Runtime/UIEffect.cs b/Packages/src/Runtime/UIEffect.cs index cec8f69..26ccb15 100644 --- a/Packages/src/Runtime/UIEffect.cs +++ b/Packages/src/Runtime/UIEffect.cs @@ -2091,6 +2091,7 @@ namespace Coffee.UIEffects src.m_GradationGradient.alphaKeys); dst.m_GradationGradient.mode = src.m_GradationGradient.mode; } + dst.m_GradationOffset = src.m_GradationOffset; dst.m_GradationScale = src.m_GradationScale; dst.m_GradationRotation = src.m_GradationRotation;