Compare commits

...

18 Commits

Author SHA1 Message Date
Aaron 7b291b2190 Added conditional compilation to allow compilation without the uGUI package (#51) 2026-10-17 08:00:16 +03:00
yasirkula b0bf247aa4 Bumped version 2026-09-13 00:43:14 +03:00
Tran Khang 4e4321bdae Fixed 6.6 NullReferenceException in SpriteAtlas.GetPackedSprites (#50) 2026-09-13 00:39:56 +03:00
yasirkula 69f7ee5a27 Made changes for Unity 6.8 in advance (https://discussions.unity.com/t/path-to-coreclr-2026-upgrade-guide/1714279) 2026-04-04 20:24:49 +03:00
nnra afda67474b Fixed compiler error on Unity 6.5 (#49) 2026-03-31 11:46:41 +03:00
yasirkula 955972cc00 Fixed search getting stuck in play mode if a pending Task is searched by reflection 2026-03-19 13:55:21 +03:00
yasirkula ac55f29e7d Removed a duplicate code 2026-03-19 13:54:11 +03:00
yasirkula 8f8316266c Addressable groups are checked when Addressables support is enabled (fixed #29) 2025-12-31 12:11:51 +03:00
yasirkula 6edf344ebc Fixed prefabs' child objects' references being marked as redundant even though they aren't 2025-12-31 10:11:24 +03:00
yasirkula e80ad3b905 Fixed StackOverflowException that may occurr if there is a huge chain of linked GameObjects in the scene (fixed #45) 2025-12-28 23:59:50 +03:00
yasirkula 0342ab20c9 For simplicity's sake, removed the following search parameters that were only exposed in the code: searchNonSerializableVariables, fieldModifiers, propertyModifiers 2025-12-28 23:09:14 +03:00
yasirkula 6a158cba7e Plugin is now compatible with Unity 6.3 (fixed #46)(fixed #47) 2025-12-21 16:06:47 +03:00
yasirkula 652dbe2171 Fixed CS0649 warning in Visual Studio Error list 2025-12-21 15:15:44 +03:00
yasirkula a1b66ced77 Removed pre-2021.3 compiler directives to simplify the codebase 2025-12-21 15:15:18 +03:00
Stefan Tscheppe 2bd6a02504 Fix typo in property name used for AssetReference usage search (#48) 2025-12-10 15:59:10 +03:00
yasirkula 790a508dcd Fixed GetScreenFittedRect not working on Unity 2022.3.62+, 6.0.49+ and 6.1.0+ 2025-06-01 17:55:42 +03:00
yasirkula d6a03aa8f2 readonly struct optimization 2025-06-01 17:55:12 +03:00
yasirkula 177db66fbd Simplified Package Manager installation instruction 2025-05-30 10:25:36 +03:00
14 changed files with 414 additions and 432 deletions
+2 -2
View File
@@ -21,8 +21,8 @@ There are 5 ways to install this plugin:
- import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package* - import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package*
- clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder - clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder
- import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837) - import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837)
- *(via Package Manager)* add the following line to *Packages/manifest.json*: - *(via Package Manager)* click the + button and install the package from the following git URL:
- `"com.yasirkula.assetusagedetector": "https://github.com/yasirkula/UnityAssetUsageDetector.git",` - `https://github.com/yasirkula/UnityAssetUsageDetector.git`
- *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command: - *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command:
- `openupm add com.yasirkula.assetusagedetector` - `openupm add com.yasirkula.assetusagedetector`
@@ -2,7 +2,8 @@
"name": "AssetUsageDetector.Editor", "name": "AssetUsageDetector.Editor",
"rootNamespace": "", "rootNamespace": "",
"references": [ "references": [
"Unity.Addressables" "Unity.Addressables",
"Unity.Addressables.Editor"
], ],
"includePlatforms": [ "includePlatforms": [
"Editor" "Editor"
@@ -23,6 +24,11 @@
"name": "com.unity.visualeffectgraph", "name": "com.unity.visualeffectgraph",
"expression": "0.0.0", "expression": "0.0.0",
"define": "ASSET_USAGE_VFX_GRAPH" "define": "ASSET_USAGE_VFX_GRAPH"
},
{
"name": "com.unity.ugui",
"expression": "0.0.0",
"define": "ASSET_USAGE_UGUI"
} }
], ],
"noEngineReferences": false "noEngineReferences": false
@@ -8,9 +8,10 @@ using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER #if UNITY_6000_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; using EntityId = UnityEngine.EntityId;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; #else
using EntityId = System.Int32;
#endif #endif
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
@@ -36,10 +37,7 @@ namespace AssetUsageDetectorNamespace
public bool dontSearchInSourceAssets = true; public bool dontSearchInSourceAssets = true;
public bool searchInProjectSettings = true; public bool searchInProjectSettings = true;
public int searchDepthLimit = 4; public int searchDepthLimit = 32;
public BindingFlags fieldModifiers = BindingFlags.Public | BindingFlags.NonPublic;
public BindingFlags propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic;
public bool searchNonSerializableVariables = true;
public bool searchUnusedMaterialProperties = true; public bool searchUnusedMaterialProperties = true;
@@ -80,13 +78,12 @@ namespace AssetUsageDetectorNamespace
// An optimization to search an object only once (key is a hash of the searched object) // An optimization to search an object only once (key is a hash of the searched object)
private readonly Dictionary<string, ReferenceNode> searchedObjects = new Dictionary<string, ReferenceNode>( 4096 ); private readonly Dictionary<string, ReferenceNode> searchedObjects = new Dictionary<string, ReferenceNode>( 4096 );
private readonly Dictionary<int, ReferenceNode> searchedUnityObjects = new Dictionary<int, ReferenceNode>( 32768 ); // Unity objects use their instanceIDs as key which is more performant private readonly Dictionary<EntityId, ReferenceNode> searchedUnityObjects = new(32768); // Unity objects use their EntityIds as key
// Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function) // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
private readonly List<object> callStack = new List<object>( 64 ); private readonly List<object> callStack = new List<object>( 64 );
private Object currentSearchedObject; private Object currentSearchedObject;
private int currentDepth;
private bool searchingSourceAssets; private bool searchingSourceAssets;
private bool isInPlayMode; private bool isInPlayMode;
@@ -162,7 +159,6 @@ namespace AssetUsageDetectorNamespace
searchResult = new List<SearchResultGroup>(); // Overall search results searchResult = new List<SearchResultGroup>(); // Overall search results
currentSearchedObject = null; currentSearchedObject = null;
currentDepth = 0;
searchedObjectsCount = 0; searchedObjectsCount = 0;
searchStartTime = EditorApplication.timeSinceStartup; searchStartTime = EditorApplication.timeSinceStartup;
@@ -334,9 +330,9 @@ namespace AssetUsageDetectorNamespace
// Initialize data used by search functions // Initialize data used by search functions
InitializeSearchFunctionsData( searchParameters ); InitializeSearchFunctionsData( searchParameters );
// Initialize the nodes of searched asset(s) // Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet ) foreach (Object obj in objectsToSearchSet)
searchedUnityObjects.Add( obj.GetInstanceID(), PopReferenceNode( obj ) ); searchedUnityObjects.Add(obj.GetEntityId(), PopReferenceNode(obj));
// Progressbar values // Progressbar values
int searchProgress = 0; int searchProgress = 0;
@@ -466,10 +462,6 @@ namespace AssetUsageDetectorNamespace
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
} }
// Search non-serializable variables for references while searching a scene in play mode
if( isInPlayMode )
searchSerializableVariablesOnly = false;
if( scenesToSearch.Count > 0 ) if( scenesToSearch.Count > 0 )
{ {
// Calculate the path(s) of the scenes that won't be searched for references // Calculate the path(s) of the scenes that won't be searched for references
@@ -664,8 +656,8 @@ namespace AssetUsageDetectorNamespace
usedObjectPathsSet.Add( assetPath ); usedObjectPathsSet.Add( assetPath );
else else
{ {
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent ) for (Transform parent = ((GameObject)obj).transform.parent; parent != null; parent = parent.parent)
usedObjectPathsSet.Add( parent.gameObject.GetInstanceID().ToString() ); usedObjectPathsSet.Add(parent.gameObject.GetEntityId().ToString());
} }
} }
} }
@@ -736,14 +728,14 @@ namespace AssetUsageDetectorNamespace
{ {
if( !searchedTopmostGameObject ) if( !searchedTopmostGameObject )
{ {
if( obj is GameObject ) if (obj is GameObject)
unusedMainObjectNodes[obj.GetInstanceID().ToString()] = node; unusedMainObjectNodes[obj.GetEntityId().ToString()] = node;
else else
currentSearchResultGroup.AddReference( node ); currentSearchResultGroup.AddReference(node);
} }
else // List child GameObject scene objects under their parent GameObject else // List child GameObject scene objects under their parent GameObject
{ {
string dictionaryKey = searchedTopmostGameObject.GetInstanceID().ToString(); string dictionaryKey = searchedTopmostGameObject.GetEntityId().ToString();
List<ReferenceNode> unusedSubObjectNodesAtPath; List<ReferenceNode> unusedSubObjectNodesAtPath;
if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) ) if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) )
unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 ); unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
@@ -1008,6 +1000,10 @@ namespace AssetUsageDetectorNamespace
return cachedResult; return cachedResult;
} }
// Comply with the recursive search limit
if (callStack.Count >= searchParameters.searchDepthLimit)
return null;
searchedObjectsCount++; searchedObjectsCount++;
ReferenceNode result; ReferenceNode result;
@@ -1020,14 +1016,14 @@ namespace AssetUsageDetectorNamespace
{ {
if( assetsToSearchSet.Count == 0 ) if( assetsToSearchSet.Count == 0 )
{ {
searchedUnityObjects.Add( unityObject.GetInstanceID(), null ); searchedUnityObjects.Add(unityObject.GetEntityId(), null);
return null; return null;
} }
assetPath = AssetDatabase.GetAssetPath( unityObject ); assetPath = AssetDatabase.GetAssetPath( unityObject );
if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) ) if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) )
{ {
searchedUnityObjects.Add( unityObject.GetInstanceID(), null ); searchedUnityObjects.Add(unityObject.GetEntityId(), null);
return null; return null;
} }
} }
@@ -1069,17 +1065,11 @@ namespace AssetUsageDetectorNamespace
} }
else else
{ {
// Comply with the recursive search limit
if( currentDepth >= searchParameters.searchDepthLimit )
return null;
callStack.Add( obj ); callStack.Add( obj );
currentDepth++;
result = PopReferenceNode( obj ); result = PopReferenceNode( obj );
SearchVariablesWithReflection( result ); SearchVariablesWithReflection( result );
currentDepth--;
callStack.RemoveAt( callStack.Count - 1 ); callStack.RemoveAt( callStack.Count - 1 );
} }
@@ -1089,24 +1079,23 @@ namespace AssetUsageDetectorNamespace
result = null; result = null;
} }
// Cache the search result if we are skimming through a class (not a struct; i.e. objHash != null) // Cache the search result if we are skimming through a class (not a struct) and if the object is a UnityEngine.Object (if not,
// and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something // cache the result only if we have actually found something or we are at the root of the search; i.e. callStack.Count == 0)
// or we are at the root of the search; i.e. currentDepth == 0) if (obj is not ValueType && (result != null || unityObject != null || callStack.Count == 0))
if( !( obj is ValueType ) && ( result != null || unityObject != null || currentDepth == 0 ) ) {
{ if (!searchingSourceAsset)
if( !searchingSourceAsset ) {
{ if (obj is Object)
if( obj is Object ) searchedUnityObjects.Add(unityObject.GetEntityId(), result);
searchedUnityObjects.Add( unityObject.GetInstanceID(), result ); else
else searchedObjects.Add(GetNodeObjectHash(obj), result);
searchedObjects.Add( GetNodeObjectHash( obj ), result ); }
} else if (result != null)
else if( result != null ) {
{ result.CopyReferencesTo(searchedUnityObjects[unityObject.GetEntityId()]);
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetInstanceID()] ); PoolReferenceNode(result);
PoolReferenceNode( result ); }
} }
}
return result; return result;
} }
@@ -1232,46 +1221,46 @@ namespace AssetUsageDetectorNamespace
return false; return false;
} }
// If object was already searched, return its ReferenceNode // If object was already searched, return its ReferenceNode
private bool TryGetReferenceNode( object nodeObject, out ReferenceNode referenceNode ) private bool TryGetReferenceNode(object nodeObject, out ReferenceNode referenceNode)
{ {
if( nodeObject is Object ) if (nodeObject is Object unityObject)
{ {
if( searchedUnityObjects.TryGetValue( ( (Object) nodeObject ).GetInstanceID(), out referenceNode ) ) if (searchedUnityObjects.TryGetValue(unityObject.GetEntityId(), out referenceNode))
return true; return true;
} }
else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) ) else if (searchedObjects.TryGetValue(GetNodeObjectHash(nodeObject), out referenceNode))
return true; return true;
referenceNode = null; referenceNode = null;
return false; return false;
} }
// Get reference node for object // Get reference node for object
private ReferenceNode GetReferenceNode( object nodeObject ) private ReferenceNode GetReferenceNode(object nodeObject)
{ {
ReferenceNode result; ReferenceNode result;
if( nodeObject is Object ) if (nodeObject is Object unityObject)
{ {
int hash = ( (Object) nodeObject ).GetInstanceID(); EntityId hash = unityObject.GetEntityId();
if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null ) if (!searchedUnityObjects.TryGetValue(hash, out result) || result == null)
{ {
result = PopReferenceNode( nodeObject ); result = PopReferenceNode(nodeObject);
searchedUnityObjects[hash] = result; searchedUnityObjects[hash] = result;
} }
} }
else else
{ {
string hash = GetNodeObjectHash( nodeObject ); string hash = GetNodeObjectHash(nodeObject);
if( !searchedObjects.TryGetValue( hash, out result ) || result == null ) if (!searchedObjects.TryGetValue(hash, out result) || result == null)
{ {
result = PopReferenceNode( nodeObject ); result = PopReferenceNode(nodeObject);
searchedObjects[hash] = result; searchedObjects[hash] = result;
} }
} }
return result; return result;
} }
// Fetch a reference node from pool // Fetch a reference node from pool
private ReferenceNode PopReferenceNode( object nodeObject ) private ReferenceNode PopReferenceNode( object nodeObject )
@@ -5,13 +5,19 @@ using System.IO;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using UnityEditor; using UnityEditor;
#if ASSET_USAGE_ADDRESSABLES
using UnityEditor.AddressableAssets.Settings;
#endif
using UnityEditor.Animations; using UnityEditor.Animations;
using UnityEngine; using UnityEngine;
#if ASSET_USAGE_UGUI
using UnityEngine.UI; using UnityEngine.UI;
#endif
using UnityEngine.U2D; using UnityEngine.U2D;
using UnityEngine.Playables; using UnityEngine.Playables;
using UnityEditor.U2D; using UnityEditor.U2D;
using UnityEditor.Compilation; using UnityEditor.Compilation;
using UnityEngine.Rendering;
using UnityEngine.Tilemaps; using UnityEngine.Tilemaps;
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets;
@@ -23,6 +29,7 @@ namespace AssetUsageDetectorNamespace
public partial class AssetUsageDetector public partial class AssetUsageDetector
{ {
#region Helper Classes #region Helper Classes
#pragma warning disable 0649
[Serializable] [Serializable]
private struct AssemblyDefinitionReferences private struct AssemblyDefinitionReferences
{ {
@@ -142,6 +149,7 @@ namespace AssetUsageDetectorNamespace
return null; return null;
} }
} }
#pragma warning restore 0649
#endregion #endregion
// Dictionary to quickly find the function to search a specific type with // Dictionary to quickly find the function to search a specific type with
@@ -170,31 +178,25 @@ namespace AssetUsageDetectorNamespace
private bool searchMonoBehavioursForScript; private bool searchMonoBehavioursForScript;
private bool searchTextureReferences; private bool searchTextureReferences;
private bool searchShaderGraphsForSubGraphs; private bool searchShaderGraphsForSubGraphs;
private bool searchSerializableVariablesOnly;
private bool prevSearchSerializableVariablesOnly;
private BindingFlags fieldModifiers, propertyModifiers;
private BindingFlags prevFieldModifiers, prevPropertyModifiers;
// Unity's internal function that returns a SerializedProperty's corresponding FieldInfo // Unity's internal function that returns a SerializedProperty's corresponding FieldInfo
private delegate FieldInfo FieldInfoGetter( SerializedProperty p, out Type t ); private delegate FieldInfo FieldInfoGetter( SerializedProperty p, out Type t );
private readonly FieldInfoGetter fieldInfoGetter = (FieldInfoGetter) Delegate.CreateDelegate( typeof( FieldInfoGetter ), typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoAndStaticTypeFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) ); private readonly FieldInfoGetter fieldInfoGetter = (FieldInfoGetter) Delegate.CreateDelegate( typeof( FieldInfoGetter ), typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoAndStaticTypeFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly Func<Object> lightmapSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( LightmapEditorSettings ).GetMethod( "GetLightmapSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) ); private readonly Func<Object> lightmapSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( LightmapEditorSettings ).GetMethod( "GetLightmapSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly Func<Object> renderSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( RenderSettings ).GetMethod( "GetRenderSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) ); private readonly Func<Object> renderSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( RenderSettings ).GetMethod( "GetRenderSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#if UNITY_2021_2_OR_NEWER
private readonly Func<Cubemap> defaultReflectionProbeGetter = (Func<Cubemap>) Delegate.CreateDelegate( typeof( Func<Cubemap> ), typeof( RenderSettings ).GetProperty( "defaultReflection", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).GetGetMethod( true ) ); private readonly Func<Cubemap> defaultReflectionProbeGetter = (Func<Cubemap>) Delegate.CreateDelegate( typeof( Func<Cubemap> ), typeof( RenderSettings ).GetProperty( "defaultReflection", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).GetGetMethod( true ) );
#endif
internal static readonly Func<SpriteAtlas, Sprite[]> spriteAtlasPackedSpritesGetter = (Func<SpriteAtlas, Sprite[]>) Delegate.CreateDelegate( typeof( Func<SpriteAtlas, Sprite[]> ), typeof( SpriteAtlasExtensions ).GetMethod( "GetPackedSprites", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
private readonly PropertyInfo assetReferenceSubObjectTypeGetter = typeof( AssetReference ).GetProperty( "SubOjbectType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); private readonly Func<AssetReference, Type> assetReferenceSubObjectTypeGetter = (Func<AssetReference, Type>)Delegate.CreateDelegate(typeof(Func<AssetReference, Type>),
typeof(AssetReference).GetProperty("SubObjectType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)?.GetMethod
?? typeof(AssetReference).GetProperty("SubOjbectType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetMethod);
#endif #endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
private static Type vfxResourceType => typeof( Editor ).Assembly.GetType( "UnityEditor.VFX.VisualEffectResource" ) ?? Array.Find( AppDomain.CurrentDomain.GetAssemblies(), ( assembly ) => assembly.GetName().Name == "UnityEditor.VFXModule" ).GetType( "UnityEditor.VFX.VisualEffectResource" ); private static Type vfxResourceType => Type.GetType("UnityEditor.VFX.VisualEffectResource, UnityEditor.VFXModule") ?? typeof(Editor).Assembly.GetType("UnityEditor.VFX.VisualEffectResource");
private readonly Func<string, object> vfxResourceGetter = (Func<string, object>) Delegate.CreateDelegate( typeof( Func<string, object> ), vfxResourceType.GetMethod( "GetResourceAtPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) ); private readonly Func<string, object> vfxResourceGetter = (Func<string, object>) Delegate.CreateDelegate( typeof( Func<string, object> ), vfxResourceType.GetMethod( "GetResourceAtPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly MethodInfo vfxResourceContentsGetter = vfxResourceType.GetMethod( "GetContents", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ); private readonly MethodInfo vfxResourceContentsGetter = vfxResourceType.GetMethod( "GetContents", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
private readonly MethodInfo vfxSerializableObjectValueGetter = Array.Find( Array.Find( AppDomain.CurrentDomain.GetAssemblies(), ( assembly ) => assembly.GetName().Name == "Unity.VisualEffectGraph.Editor" ).GetType( "UnityEditor.VFX.VFXSerializableObject" ).GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ), ( methodInfo ) => methodInfo.Name == "Get" && !methodInfo.IsGenericMethod ); private readonly MethodInfo vfxSerializableObjectValueGetter = Array.Find(Type.GetType("UnityEditor.VFX.VFXSerializableObject, Unity.VisualEffectGraph.Editor").GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance), (methodInfo) => methodInfo.Name == "Get" && !methodInfo.IsGenericMethod);
#endif #endif
private void InitializeSearchFunctionsData( Parameters searchParameters ) private void InitializeSearchFunctionsData( Parameters searchParameters )
@@ -219,6 +221,9 @@ namespace AssetUsageDetectorNamespace
{ typeof( LightmapSettings ), SearchLightmapSettings }, { typeof( LightmapSettings ), SearchLightmapSettings },
{ typeof( RenderSettings ), SearchRenderSettings }, { typeof( RenderSettings ), SearchRenderSettings },
{ typeof( SpriteAtlas ), SearchSpriteAtlas }, { typeof( SpriteAtlas ), SearchSpriteAtlas },
#if ASSET_USAGE_ADDRESSABLES
{ typeof(AddressableAssetSettings), SearchAddressableAssetSettings },
#endif
}; };
} }
@@ -243,17 +248,6 @@ namespace AssetUsageDetectorNamespace
}; };
} }
fieldModifiers = searchParameters.fieldModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly;
propertyModifiers = searchParameters.propertyModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly;
searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables;
if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers || prevSearchSerializableVariablesOnly != searchSerializableVariablesOnly )
typeToVariables.Clear();
prevFieldModifiers = fieldModifiers;
prevPropertyModifiers = propertyModifiers;
prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly;
searchPrefabConnections = false; searchPrefabConnections = false;
searchMonoBehavioursForScript = false; searchMonoBehavioursForScript = false;
searchTextureReferences = false; searchTextureReferences = false;
@@ -641,12 +635,12 @@ namespace AssetUsageDetectorNamespace
if( searchTextureReferences && isInPlayMode && !AssetDatabase.Contains( material ) ) if( searchTextureReferences && isInPlayMode && !AssetDatabase.Contains( material ) )
{ {
Shader shader = material.shader; Shader shader = material.shader;
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); int shaderPropertyCount = shader.GetPropertyCount();
for( int i = 0; i < shaderPropertyCount; i++ ) for( int i = 0; i < shaderPropertyCount; i++ )
{ {
if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) if (shader.GetPropertyType(i) == ShaderPropertyType.Texture)
{ {
string propertyName = ShaderUtil.GetPropertyName( shader, i ); string propertyName = shader.GetPropertyName(i);
Texture assignedTexture = material.GetTexture( propertyName ); Texture assignedTexture = material.GetTexture( propertyName );
if( objectsToSearchSet.Contains( assignedTexture ) ) if( objectsToSearchSet.Contains( assignedTexture ) )
{ {
@@ -673,12 +667,12 @@ namespace AssetUsageDetectorNamespace
ShaderImporter shaderImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( shader ) ) as ShaderImporter; ShaderImporter shaderImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( shader ) ) as ShaderImporter;
if( shaderImporter != null ) if( shaderImporter != null )
{ {
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); int shaderPropertyCount = shader.GetPropertyCount();
for( int i = 0; i < shaderPropertyCount; i++ ) for( int i = 0; i < shaderPropertyCount; i++ )
{ {
if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) if (shader.GetPropertyType(i) == ShaderPropertyType.Texture)
{ {
string propertyName = ShaderUtil.GetPropertyName( shader, i ); string propertyName = shader.GetPropertyName(i);
Texture defaultTexture = shaderImporter.GetDefaultTexture( propertyName ); Texture defaultTexture = shaderImporter.GetDefaultTexture( propertyName );
if( !defaultTexture ) if( !defaultTexture )
defaultTexture = shaderImporter.GetNonModifiableTexture( propertyName ); defaultTexture = shaderImporter.GetNonModifiableTexture( propertyName );
@@ -736,7 +730,7 @@ namespace AssetUsageDetectorNamespace
VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType ); VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType );
for( int i = 0; i < variables.Length; i++ ) for( int i = 0; i < variables.Length; i++ )
{ {
if( variables[i].isSerializable && !variables[i].IsProperty ) if (!variables[i].IsProperty)
{ {
Object defaultValue = scriptImporter.GetDefaultReference( variables[i].Name ); Object defaultValue = scriptImporter.GetDefaultReference( variables[i].Name );
if( objectsToSearchSet.Contains( defaultValue ) ) if( objectsToSearchSet.Contains( defaultValue ) )
@@ -983,11 +977,7 @@ namespace AssetUsageDetectorNamespace
{ {
ReferenceNode referenceNode = PopReferenceNode( obj ); ReferenceNode referenceNode = PopReferenceNode( obj );
#if UNITY_2021_2_OR_NEWER
referenceNode.AddLinkTo( SearchObject( defaultReflectionProbeGetter() ), "Default Reflection Probe" ); referenceNode.AddLinkTo( SearchObject( defaultReflectionProbeGetter() ), "Default Reflection Probe" );
#else
referenceNode.AddLinkTo( SearchObject( ReflectionProbe.defaultTexture ), "Default Reflection Probe" );
#endif
SearchVariablesWithSerializedObject( referenceNode, true ); SearchVariablesWithSerializedObject( referenceNode, true );
return referenceNode; return referenceNode;
} }
@@ -1079,6 +1069,29 @@ namespace AssetUsageDetectorNamespace
} }
} }
#if ASSET_USAGE_ADDRESSABLES
private ReferenceNode SearchAddressableAssetSettings(object obj)
{
AddressableAssetSettings addressableSettings = (AddressableAssetSettings)obj;
ReferenceNode referenceNode = PopReferenceNode(addressableSettings);
// Search Addressable groups
foreach (Object asset in assetsToSearchSet)
{
// Don't check redundant prefab objects
if (asset is Component)
continue;
if (asset is GameObject gameObject && gameObject.transform.parent != null)
continue;
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out string guid, out long _) && addressableSettings.FindAssetEntry(guid, true) is AddressableAssetEntry addressableEntry)
referenceNode.AddLinkTo(GetReferenceNode(asset), $"Addressable: \"{addressableEntry.parentGroup.Name}\" -> \"{addressableEntry.address}\"");
}
return referenceNode;
}
#endif
// Find references from an Assembly Definition File to its Assembly Definition References // Find references from an Assembly Definition File to its Assembly Definition References
private ReferenceNode SearchAssemblyDefinitionFile( object obj ) private ReferenceNode SearchAssemblyDefinitionFile( object obj )
{ {
@@ -1387,6 +1400,7 @@ namespace AssetUsageDetectorNamespace
{ {
bool iteratingVisible = iteratorVisible.NextVisible( true ); bool iteratingVisible = iteratorVisible.NextVisible( true );
bool searchPrefabOverridesOnly = ShouldExcludeRedundantPrefabReferences( unityObject ); bool searchPrefabOverridesOnly = ShouldExcludeRedundantPrefabReferences( unityObject );
GameObject unityObjectPrefabInstanceRoot = searchPrefabOverridesOnly ? PrefabUtility.GetOutermostPrefabInstanceRoot(unityObject) : null;
bool enterChildren; bool enterChildren;
do do
{ {
@@ -1468,7 +1482,7 @@ namespace AssetUsageDetectorNamespace
// m_RD.texture is a redundant reference that shows up when searching sprites // m_RD.texture is a redundant reference that shows up when searching sprites
if( !propertyPath.EndsWithFast( "m_RD.texture" ) ) if( !propertyPath.EndsWithFast( "m_RD.texture" ) )
{ {
if( searchPrefabOverridesOnly && !iterator.prefabOverride ) if (searchPrefabOverridesOnly && !iterator.prefabOverride && ObjectBelongsToDifferentPrefabInstance(propertyValue, unityObjectPrefabInstanceRoot))
{ {
currentSearchResultGroup.NumberOfRedundantReferences++; currentSearchResultGroup.NumberOfRedundantReferences++;
enterChildren = false; enterChildren = false;
@@ -1480,6 +1494,22 @@ namespace AssetUsageDetectorNamespace
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) ) if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( unityObject, propertyValue, iterator ) ); searchParameters.searchRefactoring( new SerializedPropertyMatch( unityObject, propertyValue, iterator ) );
} }
/// Searching for references of a prefab instance's child object in either a scene or prefab mode should show the references coming from
/// that prefab instance to the child object. That's because even though <see cref="SerializedProperty.prefabOverride"/> returns
/// false for the variable that points to the child GameObject, that child GameObject is essentially different than its counterpart
/// in the prefab asset (it's an instance/clone of it after all). So no references will be reported unless we intervene.
bool ObjectBelongsToDifferentPrefabInstance(Object obj, GameObject prefabInstanceRoot)
{
if (obj == null)
return true;
GameObject objPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(obj);
if (objPrefabInstanceRoot == null)
return true;
return objPrefabInstanceRoot != prefabInstanceRoot;
}
} }
} }
} }
@@ -1503,10 +1533,6 @@ namespace AssetUsageDetectorNamespace
VariableGetterHolder[] variables = GetFilteredVariablesForType( referenceNode.nodeObject.GetType() ); VariableGetterHolder[] variables = GetFilteredVariablesForType( referenceNode.nodeObject.GetType() );
for( int i = 0; i < variables.Length; i++ ) for( int i = 0; i < variables.Length; i++ )
{ {
// When possible, don't search non-serializable variables
if( searchSerializableVariablesOnly && !variables[i].isSerializable )
continue;
try try
{ {
object variableValue = variables[i].Get( referenceNode.nodeObject ); object variableValue = variables[i].Get( referenceNode.nodeObject );
@@ -1604,130 +1630,103 @@ namespace AssetUsageDetectorNamespace
validVariables.Clear(); validVariables.Clear();
// Filter the fields Type currType = type;
if( fieldModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) while( currType != typeof( object ) )
{ {
Type currType = type; foreach (FieldInfo field in currType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
while( currType != typeof( object ) )
{ {
FieldInfo[] fields = currType.GetFields( fieldModifiers ); // Skip obsolete fields
for( int i = 0; i < fields.Length; i++ ) if( Attribute.IsDefined( field, typeof( ObsoleteAttribute ) ) )
{ continue;
FieldInfo field = fields[i];
// Skip obsolete fields // Skip primitive types
if( Attribute.IsDefined( field, typeof( ObsoleteAttribute ) ) ) if( field.FieldType.IsIgnoredUnityType() )
continue; continue;
// Skip primitive types // Additional filtering for fields:
if( field.FieldType.IsIgnoredUnityType() ) #if ASSET_USAGE_UGUI
continue; // 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components
string fieldName = field.Name;
#if UNITY_2021_2_OR_NEWER if( typeof( Graphic ).IsAssignableFrom( currType ) &&
// "ref struct"s can't be accessed via reflection ( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) )
if( field.FieldType.IsByRefLike ) continue;
continue;
#endif #endif
// Additional filtering for fields: VariableGetVal getter = field.CreateGetter( type );
// 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components if (getter != null)
string fieldName = field.Name; validVariables.Add(new VariableGetterHolder(field, getter));
if( typeof( Graphic ).IsAssignableFrom( currType ) &&
( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) )
continue;
VariableGetVal getter = field.CreateGetter( type );
if( getter != null )
validVariables.Add( new VariableGetterHolder( field, getter, searchSerializableVariablesOnly ? field.IsSerializable() : true ) );
}
currType = currType.BaseType;
} }
}
if( propertyModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) foreach (PropertyInfo property in currType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Type currType = type;
while( currType != typeof( object ) )
{ {
PropertyInfo[] properties = currType.GetProperties( propertyModifiers ); // Skip obsolete properties
for( int i = 0; i < properties.Length; i++ ) if( Attribute.IsDefined( property, typeof( ObsoleteAttribute ) ) )
{ continue;
PropertyInfo property = properties[i];
// Skip obsolete properties // Skip primitive types
if( Attribute.IsDefined( property, typeof( ObsoleteAttribute ) ) ) if( property.PropertyType.IsIgnoredUnityType() )
continue; continue;
// Skip primitive types // Skip properties without a getter function
if( property.PropertyType.IsIgnoredUnityType() ) MethodInfo propertyGetter = property.GetGetMethod( true );
continue; if( propertyGetter == null )
continue;
#if UNITY_2021_2_OR_NEWER // Skip indexer properties
// "ref struct"s can't be accessed via reflection if( property.GetIndexParameters().Length > 0 )
if( property.PropertyType.IsByRefLike ) continue;
continue;
// No need to check properties with 'override' keyword
if( propertyGetter.GetBaseDefinition().DeclaringType != propertyGetter.DeclaringType )
continue;
string propertyName = property.Name;
// Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of components to get more useful results
if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" ||
propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) )
continue;
#if ASSET_USAGE_UGUI
// Ignore "canvasRenderer" and "canvas" properties of Graphic components to get more useful results
else if( typeof( Graphic ).IsAssignableFrom( currType ) &&
( propertyName == "canvasRenderer" || propertyName == "canvas" ) )
continue;
#endif #endif
// Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak)
// Skip properties without a getter function else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" )
MethodInfo propertyGetter = property.GetGetMethod( true ); continue;
if( propertyGetter == null ) // Same as above
continue; else if( ( propertyName == "material" || propertyName == "materials" ) &&
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) ||
// Skip indexer properties typeof( Collider2D ).IsAssignableFrom( currType ) ) )
if( property.GetIndexParameters().Length > 0 ) continue;
continue; // Ignore certain Material properties that are already searched via SearchMaterial function (also, if a material doesn't have a _Color or _BaseColor
// property and its "color" property is called, it logs an error to the console, so this rule helps avoid that scenario, as well)
// No need to check properties with 'override' keyword else if( ( propertyName == "color" || propertyName == "mainTexture" ) && typeof( Material ).IsAssignableFrom( currType ) )
if( propertyGetter.GetBaseDefinition().DeclaringType != propertyGetter.DeclaringType ) continue;
continue; // Ignore "parameters" property of Animator since it doesn't contain any useful data and logs a warning to the console when Animator is inactive
else if( typeof( Animator ).IsAssignableFrom( currType ) && propertyName == "parameters" )
string propertyName = property.Name; continue;
// Ignore "spriteAnimator" property of TMP_Text component because this property adds a TMP_SpriteAnimator component to the object if it doesn't exist
// Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of components to get more useful results else if( propertyName == "spriteAnimator" && currType.Name == "TMP_Text" )
if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" || continue;
propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) ) // Ignore "meshFilter" property of TextMeshPro and TMP_SubMesh components because this property adds a MeshFilter component to the object if it doesn't exist
continue; else if( propertyName == "meshFilter" && ( currType.Name == "TextMeshPro" || currType.Name == "TMP_SubMesh" ) )
// Ignore "canvasRenderer" and "canvas" properties of Graphic components to get more useful results continue;
else if( typeof( Graphic ).IsAssignableFrom( currType ) && // Ignore "users" property of TerrainData because it returns the Terrains in the scene that use that TerrainData. This causes issues with callStack because TerrainData
( propertyName == "canvasRenderer" || propertyName == "canvas" ) ) // is already in callStack when Terrains are searched via "users" property of it and hence, Terrain->TerrainData references for that TerrainData can't be found in scenes
continue; // (this is how callStack works, it prevents searching an object if it's already in callStack to avoid infinite recursion)
// Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak) else if( propertyName == "users" && typeof( TerrainData ).IsAssignableFrom( currType ) )
else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" ) continue;
continue; else
// Same as above {
else if( ( propertyName == "material" || propertyName == "materials" ) && VariableGetVal getter = property.CreateGetter();
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) || if (getter != null)
typeof( Collider2D ).IsAssignableFrom( currType ) ) ) validVariables.Add(new VariableGetterHolder(property, getter));
continue;
// Ignore certain Material properties that are already searched via SearchMaterial function (also, if a material doesn't have a _Color or _BaseColor
// property and its "color" property is called, it logs an error to the console, so this rule helps avoid that scenario, as well)
else if( ( propertyName == "color" || propertyName == "mainTexture" ) && typeof( Material ).IsAssignableFrom( currType ) )
continue;
// Ignore "parameters" property of Animator since it doesn't contain any useful data and logs a warning to the console when Animator is inactive
else if( typeof( Animator ).IsAssignableFrom( currType ) && propertyName == "parameters" )
continue;
// Ignore "spriteAnimator" property of TMP_Text component because this property adds a TMP_SpriteAnimator component to the object if it doesn't exist
else if( propertyName == "spriteAnimator" && currType.Name == "TMP_Text" )
continue;
// Ignore "meshFilter" property of TextMeshPro and TMP_SubMesh components because this property adds a MeshFilter component to the object if it doesn't exist
else if( propertyName == "meshFilter" && ( currType.Name == "TextMeshPro" || currType.Name == "TMP_SubMesh" ) )
continue;
// Ignore "users" property of TerrainData because it returns the Terrains in the scene that use that TerrainData. This causes issues with callStack because TerrainData
// is already in callStack when Terrains are searched via "users" property of it and hence, Terrain->TerrainData references for that TerrainData can't be found in scenes
// (this is how callStack works, it prevents searching an object if it's already in callStack to avoid infinite recursion)
else if( propertyName == "users" && typeof( TerrainData ).IsAssignableFrom( currType ) )
continue;
else
{
VariableGetVal getter = property.CreateGetter();
if( getter != null )
validVariables.Add( new VariableGetterHolder( property, getter, searchSerializableVariablesOnly ? property.IsSerializable() : true ) );
}
} }
currType = currType.BaseType;
} }
currType = currType.BaseType;
} }
result = validVariables.ToArray(); result = validVariables.ToArray();
@@ -1816,41 +1815,39 @@ namespace AssetUsageDetectorNamespace
} }
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
private Object GetAddressablesAssetReferenceValue( AssetReference assetReference ) private Object GetAddressablesAssetReferenceValue(AssetReference assetReference)
{ {
Object result = assetReference.editorAsset; Object result = assetReference.editorAsset;
if( !result ) if (result == null)
return null; return null;
string subObjectName = assetReference.SubObjectName; string subObjectName = assetReference.SubObjectName;
if( !string.IsNullOrEmpty( subObjectName ) ) if (string.IsNullOrEmpty(subObjectName))
{ return result;
if( result is SpriteAtlas )
{
Sprite[] packedSprites = spriteAtlasPackedSpritesGetter( (SpriteAtlas) result );
if( packedSprites != null )
{
for( int i = 0; i < packedSprites.Length; i++ )
{
if( packedSprites[i] && packedSprites[i].name == subObjectName )
return packedSprites[i];
}
}
}
else
{
Type subObjectType = (Type) assetReferenceSubObjectTypeGetter.GetValue( assetReference, null ) ?? typeof( Object );
Object[] subAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( result ) );
for( int k = 0; k < subAssets.Length; k++ )
{
if( subAssets[k] && subAssets[k].name == subObjectName && subObjectType.IsAssignableFrom( subAssets[k].GetType() ) )
return subAssets[k];
}
}
}
return result; Type subObjectType = assetReferenceSubObjectTypeGetter(assetReference) ?? typeof(Object);
} if (subObjectType.IsAssignableFrom(result.GetType()))
return result;
if (result is SpriteAtlas spriteAtlas)
{
foreach (Sprite sprite in spriteAtlas.GetPackedSprites())
{
if (sprite != null && sprite.name == subObjectName)
return sprite;
}
}
else
{
foreach (Object subAsset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(result)))
{
if (subAsset != null && subAsset.name == subObjectName && subObjectType.IsAssignableFrom(subAsset.GetType()))
return subAsset;
}
}
return result;
}
#endif #endif
private bool ShouldExcludeRedundantPrefabReferences( Object obj ) private bool ShouldExcludeRedundantPrefabReferences( Object obj )
@@ -1895,4 +1892,4 @@ namespace AssetUsageDetectorNamespace
return ( component != null && !component.Equals( null ) ) ? component.gameObject : obj; return ( component != null && !component.Equals( null ) ) ? component.gameObject : obj;
} }
} }
} }
@@ -1,15 +1,9 @@
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
{ {
@@ -24,10 +18,6 @@ namespace AssetUsageDetectorNamespace
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch"; private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch"; private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc"; private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties";
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps"; private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch"; private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
@@ -92,13 +82,10 @@ namespace AssetUsageDetectorNamespace
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool lazySceneSearch = true; private bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
private bool addressablesSupport = false; private bool addressablesSupport = false;
#endif #endif
private bool searchNonSerializableVariables = true;
private bool searchUnusedMaterialProperties = true; private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false; private bool calculateUnusedObjects = false;
private bool hideDuplicateRows = true; private bool hideDuplicateRows = true;
@@ -107,8 +94,6 @@ namespace AssetUsageDetectorNamespace
private bool noAssetDatabaseChanges = false; private bool noAssetDatabaseChanges = false;
private bool showDetailedProgressBar = true; private bool showDetailedProgressBar = true;
private BindingFlags fieldModifiers, propertyModifiers;
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer(); private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
@@ -299,10 +284,6 @@ namespace AssetUsageDetectorNamespace
searchInAssetsFolder = searchParameters.searchInAssetsFolder; searchInAssetsFolder = searchParameters.searchInAssetsFolder;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchInProjectSettings = searchParameters.searchInProjectSettings; searchInProjectSettings = searchParameters.searchInProjectSettings;
searchDepthLimit = searchParameters.searchDepthLimit;
fieldModifiers = searchParameters.fieldModifiers;
propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties; searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring; searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch; lazySceneSearch = searchParameters.lazySceneSearch;
@@ -379,10 +360,6 @@ namespace AssetUsageDetectorNamespace
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder ); EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets ); EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings ); EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers );
EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers );
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties ); EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch ); EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
@@ -402,10 +379,6 @@ namespace AssetUsageDetectorNamespace
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true ); searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true ); dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true ); searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
fieldModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_FIELDS, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
propertyModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_PROPERTIES, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true ); searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true ); lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
@@ -687,10 +660,6 @@ namespace AssetUsageDetectorNamespace
dontSearchInSourceAssets = dontSearchInSourceAssets, dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null, excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
searchInProjectSettings = searchInProjectSettings, searchInProjectSettings = searchInProjectSettings,
//fieldModifiers = fieldModifiers,
//propertyModifiers = propertyModifiers,
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties, searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring, searchRefactoring = searchRefactoring,
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
@@ -99,15 +99,11 @@ namespace AssetUsageDetectorNamespace
// Add Sprites of SpriteAtlases to the sub-assets list // Add Sprites of SpriteAtlases to the sub-assets list
if( target is SpriteAtlas spriteAtlas ) if( target is SpriteAtlas spriteAtlas )
{ {
Sprite[] packedSprites = AssetUsageDetector.spriteAtlasPackedSpritesGetter( spriteAtlas ); foreach (Sprite sprite in spriteAtlas.GetPackedSprites())
if( packedSprites != null ) {
{ if (sprite != null && currentSubAssets.Add(sprite))
for( int i = 0; i < packedSprites.Length; i++ ) subAssets.Add(new SubAsset(sprite, shouldSearchChildren ?? true));
{ }
if( packedSprites[i] != null && currentSubAssets.Add( packedSprites[i] ) )
subAssets.Add( new SubAsset( packedSprites[i], shouldSearchChildren ?? true ) );
}
}
} }
// Find sub-asset(s) of the asset (if any) // Find sub-asset(s) of the asset (if any)
@@ -5,6 +5,7 @@ using System.Reflection;
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement; using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
using UnityEngine.Rendering;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
@@ -265,7 +266,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < MonoScriptAllVariables.Length; i++ ) for( int i = 0; i < MonoScriptAllVariables.Length; i++ )
{ {
if( MonoScriptAllVariables[i].isSerializable && !MonoScriptAllVariables[i].IsProperty ) if (!MonoScriptAllVariables[i].IsProperty)
{ {
Object variableDefaultValue = monoImporter.GetDefaultReference( MonoScriptAllVariables[i].Name ); Object variableDefaultValue = monoImporter.GetDefaultReference( MonoScriptAllVariables[i].Name );
if( variableDefaultValue == Value && MonoScriptAllVariables[i].Name == Variable ) if( variableDefaultValue == Value && MonoScriptAllVariables[i].Name == Variable )
@@ -289,14 +290,14 @@ namespace AssetUsageDetectorNamespace
List<string> nonModifiableTextureNames = new List<string>( 16 ); List<string> nonModifiableTextureNames = new List<string>( 16 );
List<Texture> nonModifiableTextureValues = new List<Texture>( 16 ); List<Texture> nonModifiableTextureValues = new List<Texture>( 16 );
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); int shaderPropertyCount = shader.GetPropertyCount();
for( int i = 0; i < shaderPropertyCount; i++ ) for( int i = 0; i < shaderPropertyCount; i++ )
{ {
if( ShaderUtil.GetPropertyType( shader, i ) != ShaderUtil.ShaderPropertyType.TexEnv ) if (shader.GetPropertyType(i) != ShaderPropertyType.Texture)
continue; continue;
string propertyName = ShaderUtil.GetPropertyName( shader, i ); string propertyName = shader.GetPropertyName(i);
if( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) ) if ((shader.GetPropertyFlags(i) & ShaderPropertyFlags.NonModifiableTextureData) != 0)
{ {
Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName ); Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable ) if( propertyDefaultValue == Value && propertyName == Variable )
@@ -9,6 +9,14 @@ using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_6000_3_OR_NEWER
using EntityId = UnityEngine.EntityId;
#else
using EntityId = System.Int32;
#endif
#if UNITY_6000_2_OR_NEWER
using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<int>;
#endif
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
{ {
@@ -39,7 +47,7 @@ namespace AssetUsageDetectorNamespace
} }
public string label; public string label;
public int instanceId; public EntityId instanceId;
public bool isUnityObject, isMainReference; public bool isUnityObject, isMainReference;
public ReferenceNode.UsedState usedState; public ReferenceNode.UsedState usedState;
@@ -1127,8 +1135,8 @@ namespace AssetUsageDetectorNamespace
public bool IsMainReference { get; private set; } // True: if belongs to a scene search result group, then it's an object in that scene. If belongs to the assets search result group, then it's an asset public bool IsMainReference { get; private set; } // True: if belongs to a scene search result group, then it's an object in that scene. If belongs to the assets search result group, then it's an asset
internal object nodeObject; internal object nodeObject;
private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise private EntityId? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise
public Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } } public Object UnityObject => instanceId.HasValue ? Utilities.EntityIdToObject(instanceId.Value) : null;
private readonly List<Link> links = new List<Link>( 2 ); private readonly List<Link> links = new List<Link>( 2 );
public int NumberOfOutgoingLinks { get { return links.Count; } } public int NumberOfOutgoingLinks { get { return links.Count; } }
@@ -1222,7 +1230,7 @@ namespace AssetUsageDetectorNamespace
Object unityObject = nodeObject as Object; Object unityObject = nodeObject as Object;
if( unityObject != null ) if( unityObject != null )
{ {
instanceId = unityObject.GetInstanceID(); instanceId = unityObject.GetEntityId();
Label = unityObject.name + " (" + unityObject.GetType().Name + ")"; Label = unityObject.name + " (" + unityObject.GetType().Name + ")";
if( AssetUsageDetectorSettings.ShowRootAssetName && unityObject.IsAsset() && !AssetDatabase.IsMainAsset( unityObject ) ) if( AssetUsageDetectorSettings.ShowRootAssetName && unityObject.IsAsset() && !AssetDatabase.IsMainAsset( unityObject ) )
@@ -1360,7 +1368,7 @@ namespace AssetUsageDetectorNamespace
{ {
label = Label, label = Label,
isMainReference = IsMainReference, isMainReference = IsMainReference,
instanceId = instanceId ?? 0, instanceId = instanceId ?? default,
isUnityObject = instanceId.HasValue, isUnityObject = instanceId.HasValue,
usedState = usedState usedState = usedState
}; };
@@ -1410,4 +1418,4 @@ namespace AssetUsageDetectorNamespace
return uid; return uid;
} }
} }
} }
@@ -26,11 +26,20 @@ namespace AssetUsageDetectorNamespace
public static void Show( Rect sourcePosition, string tooltip ) public static void Show( Rect sourcePosition, string tooltip )
{ {
// Don't lose focus to the previous window
EditorWindow prevFocusedWindow = focusedWindow;
if (!mainWindow)
{
mainWindow = CreateInstance<SearchResultTooltip>();
mainWindow.ShowPopup();
}
Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical ); Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical );
Rect preferredPosition; Rect preferredPosition;
Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize ); Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize );
Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect( positionLeft ); Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect(positionLeft, mainWindow);
Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position; Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position;
Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size; Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size;
@@ -39,7 +48,7 @@ namespace AssetUsageDetectorNamespace
else else
{ {
Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize ); Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize );
Rect screenFittedPositionRight = Utilities.GetScreenFittedRect( positionRight ); Rect screenFittedPositionRight = Utilities.GetScreenFittedRect(positionRight, mainWindow);
Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position; Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position;
Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size; Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size;
@@ -49,15 +58,6 @@ namespace AssetUsageDetectorNamespace
preferredPosition = screenFittedPositionLeft; preferredPosition = screenFittedPositionLeft;
} }
// Don't lose focus to the previous window
EditorWindow prevFocusedWindow = focusedWindow;
if( !mainWindow )
{
mainWindow = CreateInstance<SearchResultTooltip>();
mainWindow.ShowPopup();
}
SearchResultTooltip.tooltip = tooltip; SearchResultTooltip.tooltip = tooltip;
mainWindow.minSize = preferredPosition.size; mainWindow.minSize = preferredPosition.size;
mainWindow.position = preferredPosition; mainWindow.position = preferredPosition;
@@ -4,13 +4,12 @@ using System.Reflection;
using System.Text; using System.Text;
using UnityEditor; using UnityEditor;
using UnityEditor.IMGUI.Controls; using UnityEditor.IMGUI.Controls;
using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
#if UNITY_2021_2_OR_NEWER #if UNITY_6000_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage; using TreeView = UnityEditor.IMGUI.Controls.TreeView<int>;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility; using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<int>;
#elif UNITY_2018_3_OR_NEWER using TreeViewState = UnityEditor.IMGUI.Controls.TreeViewState<int>;
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif #endif
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
@@ -1311,7 +1310,7 @@ namespace AssetUsageDetectorNamespace
if( preferredHeight > 10f ) if( preferredHeight > 10f )
{ {
Vector2 size = position.size; Vector2 size = position.size;
position = Utilities.GetScreenFittedRect( new Rect( GUIUtility.GUIToScreenPoint( Event.current.mousePosition ) + new Vector2( size.x * -0.5f, 10f ), size ) ); position = Utilities.GetScreenFittedRect(new Rect(GUIUtility.GUIToScreenPoint(Event.current.mousePosition) + new Vector2(size.x * -0.5f, 10f), size), this);
shouldRepositionSelf = false; shouldRepositionSelf = false;
GUIUtility.ExitGUI(); GUIUtility.ExitGUI();
+91 -71
View File
@@ -2,16 +2,15 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks;
using Unity.Collections; using Unity.Collections;
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement; using UnityEditor.SceneManagement;
using UnityEditor.U2D;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using UnityEngine.U2D;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
{ {
@@ -43,7 +42,9 @@ namespace AssetUsageDetectorNamespace
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace; private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace; private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
private static MethodInfo screenFittedRectGetter; private static MethodInfo screenFittedRectGetter;
private static FieldInfo editorWindowHostViewGetter;
private static PropertyInfo hostViewContainerWindowGetter;
private static readonly Func<Object, bool, bool> prefabHasAnyOverridesGetter = (Func<Object, bool, bool>) Delegate.CreateDelegate( typeof( Func<Object, bool, bool> ), typeof( PrefabUtility ).GetMethod( "HasObjectOverride", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) ); private static readonly Func<Object, bool, bool> prefabHasAnyOverridesGetter = (Func<Object, bool, bool>) Delegate.CreateDelegate( typeof( Func<Object, bool, bool> ), typeof( PrefabUtility ).GetMethod( "HasObjectOverride", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
@@ -176,6 +177,28 @@ namespace AssetUsageDetectorNamespace
return false; return false;
} }
#if UNITY_6000_3_OR_NEWER
public static EntityId GetEntityId(this Object obj)
{
return obj.GetEntityId();
}
public static Object EntityIdToObject(EntityId entityId)
{
return EditorUtility.EntityIdToObject(entityId);
}
#else
public static int GetEntityId(this Object obj)
{
return obj.GetInstanceID();
}
public static Object EntityIdToObject(int instanceID)
{
return EditorUtility.InstanceIDToObject(instanceID);
}
#endif
// Returns an enumerator to iterate through all asset paths in the folder // Returns an enumerator to iterate through all asset paths in the folder
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset ) public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
{ {
@@ -325,61 +348,6 @@ namespace AssetUsageDetectorNamespace
return t1.GetSiblingIndex() - t2.GetSiblingIndex(); return t1.GetSiblingIndex() - t2.GetSiblingIndex();
} }
// Check if the field is serializable
public static bool IsSerializable( this FieldInfo fieldInfo )
{
// See Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( fieldInfo.IsInitOnly )
return false;
// SerializeReference makes even System.Object fields serializable
if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) )
return true;
if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) )
return false;
return IsTypeSerializable( fieldInfo.FieldType );
}
// Check if the property is serializable
public static bool IsSerializable( this PropertyInfo propertyInfo )
{
return IsTypeSerializable( propertyInfo.PropertyType );
}
// Check if type is serializable
private static bool IsTypeSerializable( Type type )
{
// see Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
if( type.IsArray )
{
if( type.GetArrayRank() != 1 )
return false;
type = type.GetElementType();
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
else if( type.IsGenericType )
{
// Generic types are allowed on 2020.1 and later
if( type.GetGenericTypeDefinition() == typeof( List<> ) )
{
type = type.GetGenericArguments()[0];
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
}
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
}
// Check if instances of this type should be searched for references // Check if instances of this type should be searched for references
public static bool IsIgnoredUnityType( this Type type ) public static bool IsIgnoredUnityType( this Type type )
{ {
@@ -394,9 +362,13 @@ namespace AssetUsageDetectorNamespace
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace ) if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
return true; return true;
// Searching pointers or ref variables for reference throws ArgumentException // Searching Tasks for reference may freeze Unity since Task.Result freezes the active thread if Task hasn't completed yet
if( type.IsPointer || type.IsByRef ) if (typeof(Task).IsAssignableFrom(type))
return true; return true;
// Searching pointers, ref variables or ref structs for reference throws ArgumentException
if (type.IsPointer || type.IsByRef || type.IsByRefLike)
return true;
return false; return false;
} }
@@ -494,14 +466,25 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 4f ); GUILayout.Space( 4f );
} }
// Restricts the given Rect within the screen's bounds /// <summary>
public static Rect GetScreenFittedRect( Rect originalRect ) /// Restricts the given Rect within the screen's bounds.
{ /// </summary>
if( screenFittedRectGetter == null ) public static Rect GetScreenFittedRect(Rect originalRect, EditorWindow editorWindow)
screenFittedRectGetter = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.ContainerWindow" ).GetMethod( "FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ); {
screenFittedRectGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.ContainerWindow").GetMethod("FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
return (Rect) screenFittedRectGetter.Invoke( null, new object[3] { originalRect, true, true } ); if (screenFittedRectGetter.GetParameters().Length == 3)
} return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, true, true });
else
{
// New version introduced in Unity 2022.3.62f1, Unity 6.0.49f1 and Unity 6.1.0f1.
// Usage example: https://github.com/Unity-Technologies/UnityCsReference/blob/10f8718268a7e34844ba7d59792117c28d75a99b/Editor/Mono/EditorWindow.cs#L1264
editorWindowHostViewGetter ??= typeof(EditorWindow).GetField("m_Parent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
hostViewContainerWindowGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.HostView").GetProperty("window", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, originalRect.center, true, hostViewContainerWindowGetter.GetValue(editorWindowHostViewGetter.GetValue(editorWindow), null) });
}
}
// Check if all the objects inside the list are null // Check if all the objects inside the list are null
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch ) public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
@@ -583,5 +566,42 @@ namespace AssetUsageDetectorNamespace
return false; return false;
} }
public static List<Sprite> GetPackedSprites(this SpriteAtlas spriteAtlas)
{
SpriteAtlas masterAtlas = spriteAtlas.isVariant ? spriteAtlas.GetMasterAtlas() : null;
Object[] packables = (masterAtlas != null) ? masterAtlas.GetPackables() : spriteAtlas.GetPackables();
List<Sprite> result = new(packables.Length);
foreach (Object packable in packables)
{
if (packable == null)
continue;
if (packable.IsFolder())
{
foreach (string guid in AssetDatabase.FindAssets("t:Sprite", new[] { AssetDatabase.GetAssetPath(packable) }))
{
foreach (Object asset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GUIDToAssetPath(guid)))
{
if (asset is Sprite sprite)
result.Add(sprite);
}
}
}
else if (packable is Texture2D)
{
foreach (Object asset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(packable)))
{
if (asset is Sprite sprite)
result.Add(sprite);
}
}
else if (packable is Sprite sprite)
result.Add(sprite);
}
return result;
}
} }
} }
@@ -9,30 +9,27 @@ namespace AssetUsageDetectorNamespace
public delegate object VariableGetVal( object obj ); public delegate object VariableGetVal( object obj );
// Custom struct to hold a variable, its important properties and its getter function // Custom struct to hold a variable, its important properties and its getter function
public struct VariableGetterHolder public readonly struct VariableGetterHolder
{ {
public readonly MemberInfo variable; public readonly MemberInfo variable;
public readonly bool isSerializable;
private readonly VariableGetVal getter; private readonly VariableGetVal getter;
public string Name { get { return variable.Name; } } public readonly string Name { get { return variable.Name; } }
public bool IsProperty { get { return variable is PropertyInfo; } } public readonly bool IsProperty { get { return variable is PropertyInfo; } }
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable ) public VariableGetterHolder(FieldInfo fieldInfo, VariableGetVal getter)
{ {
this.variable = fieldInfo; this.variable = fieldInfo;
this.isSerializable = isSerializable; this.getter = getter;
this.getter = getter; }
}
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable ) public VariableGetterHolder(PropertyInfo propertyInfo, VariableGetVal getter)
{ {
this.variable = propertyInfo; this.variable = propertyInfo;
this.isSerializable = isSerializable; this.getter = getter;
this.getter = getter; }
}
public object Get( object obj ) public readonly object Get( object obj )
{ {
try try
{ {
+1 -1
View File
@@ -1,4 +1,4 @@
= Asset Usage Detector (v2.5.6) = = Asset Usage Detector (v2.6.3) =
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com E-mail: yasirkula@gmail.com
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "com.yasirkula.assetusagedetector", "name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector", "displayName": "Asset Usage Detector",
"version": "2.5.6", "version": "2.6.3",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector", "documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases", "changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt", "licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",