Compare commits

...

1 Commits

Author SHA1 Message Date
Süleyman Yasir KULA ff193224e9 - Objects animated via Animation and/or Animator components are now searched for references
- NativeArrays are no longer searched for references, iterating over them can throw InvalidOperationException if the collection is disposed. It shouldn't matter since NativeArrays are meant to store only blittable structs which can't have any Object references (+surprisingly, it can reduce the search time substantially in some projects)
- Fixed tooltips getting culled by the AssetUsageDetector window in the search results page
2020-01-23 16:13:08 +03:00
5 changed files with 276 additions and 97 deletions
@@ -129,8 +129,11 @@ namespace AssetUsageDetectorNamespace
private readonly Dictionary<Type, VariableGetterHolder[]> typeToVariables = new Dictionary<Type, VariableGetterHolder[]>( 4096 );
// 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>( 32768 );
// An optimization to fetch an animation clip's curve bindings only once
private readonly Dictionary<AnimationClip, EditorCurveBinding[]> animationClipUniqueBindings = new Dictionary<AnimationClip, EditorCurveBinding[]>( 256 );
// An optimization to fetch the dependencies of an asset only once (key is the path of the asset)
private Dictionary<string, CacheEntry> assetDependencyCache;
private CacheEntry lastRefreshedCacheEntry;
// Dictionary to quickly find the function to search a specific type with
private Dictionary<Type, Func<Object, ReferenceNode>> typeToSearchFunction;
@@ -145,6 +148,7 @@ namespace AssetUsageDetectorNamespace
private bool searchMaterialsForTexture;
private bool searchSerializableVariablesOnly;
private bool prevSearchSerializableVariablesOnly;
private int searchDepthLimit; // Depth limit for recursively searching variables of objects
@@ -168,8 +172,6 @@ namespace AssetUsageDetectorNamespace
private readonly List<ReferenceNode> nodesPool = new List<ReferenceNode>( 32 );
private readonly List<VariableGetterHolder> validVariables = new List<VariableGetterHolder>( 32 );
private readonly string reflectionNameSpace = typeof( Assembly ).Namespace;
private string CachePath { get { return Application.dataPath + "/../Library/AssetUsageDetector.cache"; } } // Path of the cache file
// Search for references!
@@ -235,14 +237,16 @@ namespace AssetUsageDetectorNamespace
this.fieldModifiers = searchParameters.fieldModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly;
this.propertyModifiers = searchParameters.propertyModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly;
this.searchDepthLimit = searchParameters.searchDepthLimit;
this.searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables;
// Initialize commonly used variables
searchResult = new List<SearchResultGroup>(); // Overall search results
if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers )
if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers || prevSearchSerializableVariablesOnly != searchSerializableVariablesOnly )
typeToVariables.Clear();
searchedObjects.Clear();
animationClipUniqueBindings.Clear();
callStack.Clear();
objectsToSearchSet.Clear();
sceneObjectsToSearchSet.Clear();
@@ -265,6 +269,8 @@ namespace AssetUsageDetectorNamespace
foreach( var cacheEntry in assetDependencyCache.Values )
cacheEntry.searchResult = CacheEntry.Result.Unknown;
lastRefreshedCacheEntry = null;
if( typeToSearchFunction == null )
{
typeToSearchFunction = new Dictionary<Type, Func<Object, ReferenceNode>>()
@@ -287,6 +293,7 @@ namespace AssetUsageDetectorNamespace
prevFieldModifiers = fieldModifiers;
prevPropertyModifiers = propertyModifiers;
prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly;
searchPrefabConnections = false;
searchMonoBehavioursForScript = false;
@@ -428,9 +435,6 @@ namespace AssetUsageDetectorNamespace
} );
}
// By default, search only serializable variables for references
searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables;
// Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet )
searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) );
@@ -539,7 +543,7 @@ namespace AssetUsageDetectorNamespace
searchResult.Add( currentSearchResultGroup );
}
// Search non-serializable variables for references only if we are currently searching a scene and the editor is in play mode
// Search non-serializable variables for references while searching a scene in play mode
if( isInPlayMode )
searchSerializableVariablesOnly = false;
@@ -626,18 +630,17 @@ namespace AssetUsageDetectorNamespace
}
catch( Exception e )
{
Debug.LogException( e );
StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 );
sb.AppendLine( "<b>AssetUsageDetector Error:</b>" ).AppendLine();
if( callStack.Count > 0 )
{
StringBuilder sb = new StringBuilder( callStack.Count * 50 );
sb.AppendLine( "Stack contents: " );
for( int i = 0; i < callStack.Count; i++ )
for( int i = callStack.Count - 1; i >= 0; i-- )
{
sb.Append( i ).Append( ": " );
Object unityObject = callStack[i] as Object;
if( unityObject != null )
if( unityObject )
sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" );
else if( callStack[i] != null )
sb.Append( callStack[i].GetType() ).AppendLine( " object" );
@@ -645,9 +648,21 @@ namespace AssetUsageDetectorNamespace
sb.AppendLine( "<<destroyed>>" );
}
Debug.LogError( sb.ToString() );
sb.AppendLine();
}
sb.AppendLine( "Searching references of: " );
foreach( Object obj in objectsToSearchSet )
{
if( obj )
sb.Append( obj.name ).Append( " (" ).Append( obj.GetType() ).AppendLine( ")" );
}
sb.AppendLine();
sb.Append( e ).AppendLine();
Debug.LogError( sb.ToString() );
try
{
InitializeSearchResultNodes( searchResult );
@@ -1012,11 +1027,17 @@ namespace AssetUsageDetectorNamespace
// If this component is an Animation, search its animation clips for references
foreach( AnimationState anim in (Animation) component )
referenceNode.AddLinkTo( SearchObject( anim.clip ) );
// Search the objects that are animated by this Animation component for references
SearchAnimatedObjects( referenceNode );
}
else if( component is Animator )
{
// If this component is an Animator, search its animation clips for references
// If this component is an Animator, search its animation clips for references (via AnimatorController)
referenceNode.AddLinkTo( SearchObject( ( (Animator) component ).runtimeAnimatorController ) );
// Search the objects that are animated by this Animator component for references
SearchAnimatedObjects( referenceNode );
}
#if UNITY_2017_2_OR_NEWER
else if( component is Tilemap )
@@ -1227,6 +1248,85 @@ namespace AssetUsageDetectorNamespace
}
#endif
// Find references from an Animation/Animator component to the objects that it animates
private void SearchAnimatedObjects( ReferenceNode referenceNode )
{
GameObject root = ( (Component) referenceNode.nodeObject ).gameObject;
AnimationClip[] clips = AnimationUtility.GetAnimationClips( root );
for( int i = 0; i < clips.Length; i++ )
{
AnimationClip clip = clips[i];
bool isClipUnique = true;
for( int j = i - 1; j >= 0; j-- )
{
if( clips[j] == clip )
{
isClipUnique = false;
break;
}
}
if( !isClipUnique )
continue;
EditorCurveBinding[] uniqueBindings;
if( !animationClipUniqueBindings.TryGetValue( clip, out uniqueBindings ) )
{
// Calculate all the "unique" paths that the animation clip's curves have
// Both float curves (GetCurveBindings) and object reference curves (GetObjectReferenceCurveBindings) are checked
List<EditorCurveBinding> _uniqueBindings = new List<EditorCurveBinding>( 2 );
EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings( clip );
for( int j = 0; j < bindings.Length; j++ )
{
string bindingPath = bindings[j].path;
if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object
continue;
bool isBindingUnique = true;
for( int k = _uniqueBindings.Count - 1; k >= 0; k-- )
{
if( bindingPath == _uniqueBindings[k].path )
{
isBindingUnique = false;
break;
}
}
if( isBindingUnique )
_uniqueBindings.Add( bindings[j] );
}
bindings = AnimationUtility.GetObjectReferenceCurveBindings( clip );
for( int j = 0; j < bindings.Length; j++ )
{
string bindingPath = bindings[j].path;
if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object
continue;
bool isBindingUnique = true;
for( int k = _uniqueBindings.Count - 1; k >= 0; k-- )
{
if( bindingPath == _uniqueBindings[k].path )
{
isBindingUnique = false;
break;
}
}
if( isBindingUnique )
_uniqueBindings.Add( bindings[j] );
}
uniqueBindings = _uniqueBindings.ToArray();
animationClipUniqueBindings[clip] = uniqueBindings;
}
string clipName = clip.name;
for( int j = 0; j < uniqueBindings.Length; j++ )
referenceNode.AddLinkTo( SearchObject( AnimationUtility.GetAnimatedObject( root, uniqueBindings[j] ) ), "Animated via clip: " + clipName );
}
}
// Search through field and properties of an object for references with SerializedObject
private void SearchWithSerializedObject( ReferenceNode referenceNode )
{
@@ -1319,12 +1419,10 @@ namespace AssetUsageDetectorNamespace
}
}
}
catch( UnassignedReferenceException )
{ }
catch( MissingReferenceException )
{ }
catch( MissingComponentException )
{ }
catch( UnassignedReferenceException ) { }
catch( MissingReferenceException ) { }
catch( MissingComponentException ) { }
catch( NotImplementedException ) { }
}
}
@@ -1341,7 +1439,7 @@ namespace AssetUsageDetectorNamespace
// 2- skip primitive types, enums and strings
// 3- skip common Unity types that can't hold any references (e.g. Vector3, Rect, Color, Quaternion)
//
// P.S. IsPrimitiveUnityType() extension function handles steps 2) and 3)
// P.S. IsIgnoredUnityType() extension function handles steps 2) and 3)
validVariables.Clear();
@@ -1361,16 +1459,7 @@ namespace AssetUsageDetectorNamespace
continue;
// Skip primitive types
Type variableType = field.FieldType;
if( variableType.IsPrimitiveUnityType() )
continue;
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( variableType ) || variableType.Namespace == reflectionNameSpace )
continue;
// Searching pointer variables for reference throws ArgumentException
if( variableType.IsPointer )
if( field.FieldType.IsIgnoredUnityType() )
continue;
// Additional filtering for fields:
@@ -1382,7 +1471,7 @@ namespace AssetUsageDetectorNamespace
VariableGetVal getter = field.CreateGetter( type );
if( getter != null )
validVariables.Add( new VariableGetterHolder( field, getter, field.IsSerializable() ) );
validVariables.Add( new VariableGetterHolder( field, getter, searchSerializableVariablesOnly ? field.IsSerializable() : true ) );
}
currType = currType.BaseType;
@@ -1404,16 +1493,7 @@ namespace AssetUsageDetectorNamespace
continue;
// Skip primitive types
Type variableType = property.PropertyType;
if( variableType.IsPrimitiveUnityType() )
continue;
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( variableType ) || variableType.Namespace == reflectionNameSpace )
continue;
// Searching pointer variables for reference throws ArgumentException
if( variableType.IsPointer )
if( property.PropertyType.IsIgnoredUnityType() )
continue;
// Skip properties without a getter function
@@ -1458,7 +1538,7 @@ namespace AssetUsageDetectorNamespace
{
VariableGetVal getter = property.CreateGetter();
if( getter != null )
validVariables.Add( new VariableGetterHolder( property, getter, property.IsSerializable() ) );
validVariables.Add( new VariableGetterHolder( property, getter, searchSerializableVariablesOnly ? property.IsSerializable() : true ) );
}
}
@@ -1506,8 +1586,55 @@ namespace AssetUsageDetectorNamespace
FileInfo assetFile = new FileInfo( dependencies[i] );
if( !assetFile.Exists || assetFile.Length != fileSizes[i] )
{
// Although not reproduced, it is reported that this section caused StackOverflowException due to infinite loop,
// if that happens, log useful information to help reproduce the issue
if( lastRefreshedCacheEntry == cacheEntry )
{
StringBuilder sb = new StringBuilder( 1000 );
sb.AppendLine( "<b>Infinite loop while refreshing a cache entry, please report it to the author.</b>" ).AppendLine();
sb.Append( "Asset path: " ).AppendLine( assetPath );
for( int j = 0; j < 2; j++ )
{
if( j == 1 )
{
cacheEntry.Refresh( assetPath );
dependencies = cacheEntry.dependencies;
fileSizes = cacheEntry.fileSizes;
}
sb.AppendLine().AppendLine( j == 0 ? "Old Dependencies:" : "New Dependencies" );
for( int k = 0; k < dependencies.Length; k++ )
{
sb.Append( "- " ).Append( dependencies[k] );
if( Directory.Exists( dependencies[k] ) )
{
sb.Append( " (Dir)" );
if( fileSizes[k] != 0L )
sb.Append( " WasCachedAsFile: " ).Append( fileSizes[k] );
}
else
{
assetFile = new FileInfo( dependencies[k] );
sb.Append( " (File) " ).Append( "CachedSize: " ).Append( fileSizes[k] );
if( assetFile.Exists )
sb.Append( " RealSize: " ).Append( assetFile.Length );
else
sb.Append( " NoLongerExists" );
}
sb.AppendLine();
}
}
Debug.LogError( sb.ToString() );
return false;
}
cacheEntry.Refresh( assetPath );
cacheEntry.searchResult = CacheEntry.Result.Unknown;
lastRefreshedCacheEntry = cacheEntry;
return AssetHasAnyReference( assetPath );
}
@@ -1659,7 +1786,7 @@ namespace AssetUsageDetectorNamespace
catch( Exception e )
{
assetDependencyCache = null;
Debug.LogException( e );
Debug.LogWarning( "Couldn't load cache (probably cache format has changed in an update), will regenerate cache.\n" + e.ToString() );
}
}
}
@@ -523,7 +523,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant unique parts of the complete paths that start with a UnityEngine.Object", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant parts (that start with a UnityEngine.Object) of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
GUILayout.EndHorizontal();
@@ -532,7 +532,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths that are unique", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest;
GUILayout.EndHorizontal();
@@ -56,74 +56,95 @@ namespace AssetUsageDetectorNamespace.Extras
if( target == null || target.Equals( null ) )
return;
if( !target.IsAsset() || !AssetDatabase.IsMainAsset( target ) || target is SceneAsset )
return;
if( includeTarget )
if( !target.IsAsset() )
{
if( !currentSubAssets.Contains( target ) )
GameObject go = target as GameObject;
if( !go || !go.scene.IsValid() )
return;
// If this is a scene object, add its child objects to the sub-assets list
// but don't include them in the search by default
Transform goTransform = go.transform;
Transform[] children = go.GetComponentsInChildren<Transform>();
for( int i = 0; i < children.Length; i++ )
{
subAssets.Add( new SubAsset( target, true ) );
currentSubAssets.Add( target );
if( ReferenceEquals( children[i], goTransform ) )
continue;
subAssets.Add( new SubAsset( children[i].gameObject, false ) );
}
}
else
{
// If asset is a directory, add all of its contents as sub-assets recursively
if( target.IsFolder() )
{
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
if( !AssetDatabase.IsMainAsset( target ) || target is SceneAsset )
return;
}
}
// Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ )
{
Object asset = assets[i];
if( asset == null || asset.Equals( null ) || asset is Component )
continue;
if( currentSubAssets.Contains( asset ) )
continue;
if( asset != target )
if( includeTarget )
{
subAssets.Add( new SubAsset( asset, true ) );
currentSubAssets.Add( asset );
if( !currentSubAssets.Contains( target ) )
{
subAssets.Add( new SubAsset( target, true ) );
currentSubAssets.Add( target );
}
}
else
{
// If asset is a directory, add all of its contents as sub-assets recursively
if( target.IsFolder() )
{
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
return;
}
}
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
// Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ )
{
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
Object asset = assets[i];
if( asset == null || asset.Equals( null ) || asset is Component )
continue;
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
if( currentSubAssets.Contains( asset ) )
continue;
if( asset != target )
{
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
for( int k = 0; k < monoScriptGuids.Length; k++ )
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
subAssets.Add( new SubAsset( asset, true ) );
currentSubAssets.Add( asset );
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
{
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
for( int k = 0; k < monoScriptGuids.Length; k++ )
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
{
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
}
}
}
}
@@ -225,7 +225,13 @@ namespace AssetUsageDetectorNamespace
Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( parameters.tooltip ) );
size.x += 10f;
GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), parameters.tooltip, Utilities.TooltipGUIStyle );
Rect tooltipRect = new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size );
if( tooltipRect.xMin < 0f )
tooltipRect.x -= tooltipRect.xMin;
else if( tooltipRect.xMax > parameters.guiRect.width )
tooltipRect.x -= tooltipRect.xMax - parameters.guiRect.width;
GUI.Box( tooltipRect, parameters.tooltip, Utilities.TooltipGUIStyle );
}
if( parameters.shouldRefreshEditorWindow )
+28 -3
View File
@@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using System.Reflection;
#if UNITY_2018_1_OR_NEWER
using Unity.Collections;
#endif
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
@@ -36,6 +39,11 @@ namespace AssetUsageDetectorNamespace.Extras
#endif
};
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
#if UNITY_2018_1_OR_NEWER
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
#endif
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
#if UNITY_2018_3_OR_NEWER
@@ -351,10 +359,27 @@ namespace AssetUsageDetectorNamespace.Extras
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
}
// Check if the type is a common Unity type (let's call them primitives)
public static bool IsPrimitiveUnityType( this Type type )
// Check if instances of this type should be searched for references
public static bool IsIgnoredUnityType( this Type type )
{
return type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum;
if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum )
return true;
#if UNITY_2018_1_OR_NEWER
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
if( type.Namespace == nativeCollectionsNamespace )
return true;
#endif
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
return true;
// Searching pointer variables for reference throws ArgumentException
if( type.IsPointer )
return true;
return false;
}
// Get <get> function for a field