fix: fix potential NPE in code

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