Compare commits

..

4 Commits

Author SHA1 Message Date
Süleyman Yasir KULA 17d3b33e8e References from one sub-asset to the other were skipped when "Don't search 'Find references of' themselves for references" was enabled (e.g. a reference from a prefab's child A to child B was skipped while searching for B's references), now fixed. 2020-02-08 23:54:48 +03:00
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
Süleyman Yasir KULA 51abec24d7 Fixed compilation error on 2019.3 2020-01-02 14:09:12 +03:00
Süleyman Yasir KULA a29dc59a75 - Now using GUI instead of GUILayout to draw the search results which results in much better GUI performance
- Fixed a StackOverflowException
2019-11-19 23:07:25 +03:00
5 changed files with 786 additions and 288 deletions
@@ -44,7 +44,7 @@ namespace AssetUsageDetectorNamespace
public bool searchInAssetsFolder = true;
public Object[] searchInAssetsSubset = null;
public Object[] excludedAssetsFromSearch = null;
public bool dontSearchInSourceAssets = false;
public bool dontSearchInSourceAssets = true;
public Object[] excludedScenesFromSearch = null;
public int searchDepthLimit = 4;
@@ -121,6 +121,8 @@ namespace AssetUsageDetectorNamespace
private readonly HashSet<string> assetsToSearchPathsSet = new HashSet<string>();
// The root prefab objects in assetsToSearch that will be used to search for prefab references
private readonly List<GameObject> assetsToSearchRootPrefabs = new List<GameObject>( 4 );
// Path(s) of the assets that should be excluded from the search
private readonly HashSet<string> excludedAssetsPathsSet = new HashSet<string>();
// Results for the currently searched scene
private SearchResultGroup currentSearchResultGroup;
@@ -129,8 +131,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,13 +150,17 @@ namespace AssetUsageDetectorNamespace
private bool searchMaterialsForTexture;
private bool searchSerializableVariablesOnly;
private bool prevSearchSerializableVariablesOnly;
private int searchDepthLimit; // Depth limit for recursively searching variables of objects
private Object currentObject;
private Object currentSearchedObject;
private int currentDepth;
private bool dontSearchInSourceAssets;
private bool searchingSourceAssets;
private bool isInPlayMode;
#if UNITY_2018_3_OR_NEWER
private UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage;
private GameObject openPrefabStagePrefabAsset;
@@ -166,8 +175,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!
@@ -233,14 +240,17 @@ 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;
this.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
// 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();
@@ -248,6 +258,7 @@ namespace AssetUsageDetectorNamespace
assetsToSearchSet.Clear();
assetsToSearchPathsSet.Clear();
assetsToSearchRootPrefabs.Clear();
excludedAssetsPathsSet.Clear();
if( assetDependencyCache == null )
{
@@ -263,6 +274,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>>()
@@ -285,6 +298,7 @@ namespace AssetUsageDetectorNamespace
prevFieldModifiers = fieldModifiers;
prevPropertyModifiers = propertyModifiers;
prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly;
searchPrefabConnections = false;
searchMonoBehavioursForScript = false;
@@ -302,7 +316,7 @@ namespace AssetUsageDetectorNamespace
if( obj.IsFolder() )
folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) );
else
AddSearchedObjectToFilteredSets( obj );
AddSearchedObjectToFilteredSets( obj, true );
}
foreach( string filePath in folderContentsSet )
@@ -316,7 +330,7 @@ namespace AssetUsageDetectorNamespace
continue;
for( int i = 0; i < assets.Length; i++ )
AddSearchedObjectToFilteredSets( assets[i] );
AddSearchedObjectToFilteredSets( assets[i], true );
}
foreach( Object obj in objectsToSearchSet )
@@ -426,24 +440,9 @@ 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 )
{
string objHash = obj.Hash();
if( searchParameters.dontSearchInSourceAssets )
searchedObjects.Add( objHash, PopReferenceNode( obj ) );
else
{
BeginSearchObject( obj );
ReferenceNode referenceNode;
if( !searchedObjects.TryGetValue( objHash, out referenceNode ) || referenceNode == null )
searchedObjects[objHash] = PopReferenceNode( obj );
}
}
searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) );
// Progressbar values
int searchProgress = 0;
@@ -491,7 +490,6 @@ namespace AssetUsageDetectorNamespace
}
// Calculate the path(s) of the assets that won't be searched for references
HashSet<string> excludedAssetsPathsSet = new HashSet<string>();
if( searchParameters.excludedAssetsFromSearch != null )
{
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
@@ -509,9 +507,6 @@ namespace AssetUsageDetectorNamespace
}
}
if( searchParameters.dontSearchInSourceAssets )
excludedAssetsPathsSet.UnionWith( assetsToSearchPathsSet );
if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching assets", 0f ) )
throw new Exception( "Search aborted" );
@@ -549,7 +544,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;
@@ -613,6 +608,20 @@ namespace AssetUsageDetectorNamespace
searchResult.Add( currentSearchResultGroup );
}
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
if( !dontSearchInSourceAssets )
{
searchingSourceAssets = true;
foreach( Object obj in objectsToSearchSet )
{
currentSearchedObject = obj;
SearchObject( obj );
}
searchingSourceAssets = false;
}
InitializeSearchResultNodes( searchResult );
// Log some c00l stuff to console
@@ -622,18 +631,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" );
@@ -641,9 +649,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 );
@@ -656,7 +676,7 @@ namespace AssetUsageDetectorNamespace
finally
{
currentSearchResultGroup = null;
currentObject = null;
currentSearchedObject = null;
EditorUtility.ClearProgressBar();
@@ -682,7 +702,7 @@ namespace AssetUsageDetectorNamespace
}
// Checks if object is asset or scene object and adds it to the corresponding HashSet(s)
private void AddSearchedObjectToFilteredSets( Object obj )
private void AddSearchedObjectToFilteredSets( Object obj, bool expandGameObjects )
{
if( obj == null || obj.Equals( null ) )
return;
@@ -698,7 +718,7 @@ namespace AssetUsageDetectorNamespace
{
GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset );
if( prefabStageObjectSource != null )
AddSearchedObjectToFilteredSets( prefabStageObjectSource );
AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects );
}
#endif
@@ -709,7 +729,11 @@ namespace AssetUsageDetectorNamespace
string assetPath = AssetDatabase.GetAssetPath( obj );
if( !string.IsNullOrEmpty( assetPath ) )
{
assetsToSearchPathsSet.Add( assetPath );
if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
excludedAssetsPathsSet.Add( assetPath );
}
GameObject go = null;
if( obj is GameObject )
@@ -724,7 +748,6 @@ namespace AssetUsageDetectorNamespace
for( int i = assetsToSearchRootPrefabs.Count - 1; i >= 0; i-- )
{
Transform rootTransform = assetsToSearchRootPrefabs[i].transform;
if( transform.IsChildOf( rootTransform ) )
{
shouldAddRootPrefabEntry = false;
@@ -749,7 +772,7 @@ namespace AssetUsageDetectorNamespace
sceneObjectsToSearchScenesSet.Add( ( (Component) obj ).gameObject.scene.path );
}
if( obj is GameObject )
if( expandGameObjects && obj is GameObject )
{
// If searched asset is a GameObject, include its components in the search
Component[] components = ( (GameObject) obj ).GetComponents<Component>();
@@ -766,6 +789,11 @@ namespace AssetUsageDetectorNamespace
sceneObjectsToSearchSet.Add( components[i] );
}
}
else if( obj is Component )
{
// Include searched components' GameObjects in the search, as well
AddSearchedObjectToFilteredSets( ( (Component) obj ).gameObject, false );
}
}
// Search a scene for references
@@ -846,10 +874,10 @@ namespace AssetUsageDetectorNamespace
if( obj is SceneAsset )
return;
currentObject = obj;
currentSearchedObject = obj;
ReferenceNode searchResult = SearchObject( obj );
if( searchResult != null && currentSearchResultGroup != null )
if( searchResult != null )
currentSearchResultGroup.AddReference( searchResult );
}
@@ -863,16 +891,21 @@ namespace AssetUsageDetectorNamespace
if( callStack.ContainsFast( obj ) )
return null;
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
// Hashing does not work well with structs all the time, don't cache search results for structs
string objHash = null;
if( !( obj is ValueType ) )
{
objHash = obj.Hash();
// If object was searched before, return the cached result
ReferenceNode cachedResult;
if( searchedObjects.TryGetValue( objHash, out cachedResult ) )
return cachedResult;
if( !searchingSourceAsset )
{
// If object was searched before, return the cached result
ReferenceNode cachedResult;
if( searchedObjects.TryGetValue( objHash, out cachedResult ) )
return cachedResult;
}
}
searchedObjectsCount++;
@@ -881,21 +914,6 @@ namespace AssetUsageDetectorNamespace
Object unityObject = obj as Object;
if( unityObject != null )
{
// If we hit a searched asset
if( objectsToSearchSet.Contains( unityObject ) )
{
// If we were searching for references of the searched asset that we hit (or a component of it),
// ignore the hit since the searched asset doesn't have a meaningful reference to itself at the moment
// If there is a meaningful reference, it will become available when calling the SearchX functions below
if( currentObject != unityObject && ( !( unityObject is Component ) || currentObject != ( (Component) unityObject ).gameObject ) )
{
result = PopReferenceNode( unityObject );
searchedObjects.Add( objHash, result );
return result;
}
}
// If the Object is an asset, search it in detail only if its dependencies contain at least one of the searched asset(s)
if( unityObject.IsAsset() && ( assetsToSearchSet.Count == 0 || !AssetHasAnyReference( AssetDatabase.GetAssetPath( unityObject ) ) ) )
{
@@ -945,7 +963,15 @@ namespace AssetUsageDetectorNamespace
// and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something
// or we are at the root of the search; i.e. currentDepth == 0)
if( objHash != null && ( result != null || unityObject != null || currentDepth == 0 ) )
searchedObjects.Add( objHash, result );
{
if( !searchingSourceAsset )
searchedObjects.Add( objHash, result );
else if( result != null )
{
result.CopyReferencesTo( searchedObjects[objHash] );
PoolReferenceNode( result );
}
}
return result;
}
@@ -1005,11 +1031,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 )
@@ -1220,6 +1252,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 )
{
@@ -1253,12 +1364,13 @@ namespace AssetUsageDetectorNamespace
break;
}
if( searchResult != null )
if( searchResult != null && searchResult != referenceNode )
{
if( searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, "Variable: " + iterator.propertyPath );
else
PoolReferenceNode( searchResult );
string propertyPath = iterator.propertyPath;
// m_RD.texture is a redundant reference that shows up when searching sprites
if( !propertyPath.EndsWith( "m_RD.texture", StringComparison.Ordinal ) )
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath );
}
} while( iterator.NextVisible( enterChildren ) );
@@ -1292,13 +1404,8 @@ namespace AssetUsageDetectorNamespace
if( !( variableValue is ICollection ) )
{
ReferenceNode searchResult = SearchObject( variableValue );
if( searchResult != null )
{
if( searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
else
PoolReferenceNode( searchResult );
}
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
}
if( variableValue is IEnumerable && !( variableValue is Transform ) )
@@ -1309,24 +1416,17 @@ namespace AssetUsageDetectorNamespace
foreach( object element in (IEnumerable) variableValue )
{
ReferenceNode searchResult = SearchObject( element );
if( searchResult != null )
{
if( searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) );
else
PoolReferenceNode( searchResult );
}
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) );
index++;
}
}
}
catch( UnassignedReferenceException )
{ }
catch( MissingReferenceException )
{ }
catch( MissingComponentException )
{ }
catch( UnassignedReferenceException ) { }
catch( MissingReferenceException ) { }
catch( MissingComponentException ) { }
catch( NotImplementedException ) { }
}
}
@@ -1343,7 +1443,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();
@@ -1363,16 +1463,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:
@@ -1384,7 +1475,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;
@@ -1406,16 +1497,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
@@ -1449,18 +1531,18 @@ namespace AssetUsageDetectorNamespace
continue;
else if( ( propertyName == "material" || propertyName == "materials" ) &&
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) ||
typeof( Collider2D ).IsAssignableFrom( currType )
#if !UNITY_2019_3_OR_NEWER
#pragma warning disable 0618
|| typeof( GUIText ).IsAssignableFrom( currType ) ) )
typeof( GUIText ).IsAssignableFrom( currType ) ||
#pragma warning restore 0618
#endif
typeof( Collider2D ).IsAssignableFrom( currType ) ) )
continue;
else
{
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 ) );
}
}
@@ -1508,8 +1590,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 );
}
@@ -1661,7 +1790,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() );
}
}
}
@@ -194,6 +194,18 @@ namespace AssetUsageDetectorNamespace.Extras
private void OnEnable()
{
visibleWindow = this;
#if UNITY_2018_3_OR_NEWER
UnityEditor.Experimental.SceneManagement.PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
UnityEditor.Experimental.SceneManagement.PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
#endif
}
private void OnDisable()
{
#if UNITY_2018_3_OR_NEWER
UnityEditor.Experimental.SceneManagement.PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
#endif
}
private void OnDestroy()
@@ -232,7 +244,7 @@ namespace AssetUsageDetectorNamespace.Extras
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, false );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
// Fetch public, protected and private non-static fields and properties from objects by default
@@ -514,7 +526,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references (can be slow with too many references)", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full;
GUILayout.EndHorizontal();
@@ -523,7 +535,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 +544,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();
@@ -565,25 +577,7 @@ namespace AssetUsageDetectorNamespace.Extras
SavePrefs();
#if UNITY_2018_3_OR_NEWER
// Try replacing prefab stage objects with their corresponding prefab assets
var openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() )
{
GameObject openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStage.prefabAssetPath );
if( openPrefabStagePrefabAsset != null )
{
for( int i = 0; i < objectsToSearch.Count; i++ )
{
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) &&
objectsToSearch[i].obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) objectsToSearch[i].obj ) )
{
GameObject prefabStageObjectSource = ( (GameObject) objectsToSearch[i].obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset );
if( prefabStageObjectSource != null )
objectsToSearch[i].obj = prefabStageObjectSource;
}
}
}
}
ReplacePrefabStageObjectsWithAssets( UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage() );
#endif
// Start searching
@@ -609,6 +603,42 @@ namespace AssetUsageDetectorNamespace.Extras
}
}
#if UNITY_2018_3_OR_NEWER
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
public void ReplacePrefabStageObjectsWithAssets( UnityEditor.Experimental.SceneManagement.PrefabStage prefabStage )
{
if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
return;
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
if( prefabAsset == null )
return;
for( int i = 0; i < objectsToSearch.Count; i++ )
{
Object obj = objectsToSearch[i].obj;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabAsset );
if( prefabStageObjectSource != null )
objectsToSearch[i].obj = prefabStageObjectSource;
List<ObjectToSearch.SubAsset> subAssets = objectsToSearch[i].subAssets;
for( int j = 0; j < subAssets.Count; j++ )
{
obj = subAssets[j].subAsset;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabAsset );
if( prefabStageObjectSource != null )
subAssets[j].subAsset = prefabStageObjectSource;
}
}
}
}
}
#endif
private bool ReturnToSetupPhase( bool restoreInitialSceneSetup )
{
if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
@@ -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] );
}
}
}
}
+394 -102
View File
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
@@ -15,6 +16,8 @@ namespace AssetUsageDetectorNamespace
public PathDrawingMode pathDrawingMode;
public bool showTooltips;
public bool noAssetDatabaseChanges;
public Rect guiRect;
public bool shouldRefreshEditorWindow;
public string tooltip;
public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips, bool noAssetDatabaseChanges )
@@ -52,13 +55,20 @@ namespace AssetUsageDetectorNamespace
public List<string> linkDescriptions;
}
private bool success;
#pragma warning disable 1692
#pragma warning disable IDE0044
private bool success; // This is not readonly so that it can be serialized
#pragma warning restore IDE0044
#pragma warning restore 1692
private List<SearchResultGroup> result;
private SceneSetup[] initialSceneSetup;
private AssetUsageDetector searchHandler;
private AssetUsageDetector.Parameters m_searchParameters;
private float guiHeight; // Prevents scroll view's position from getting reset at domain reload
private List<SerializableNode> serializedNodes;
private List<SerializableResultGroup> serializedGroups;
@@ -147,13 +157,20 @@ namespace AssetUsageDetectorNamespace
// Make sure the AssetDatabase is up-to-date
AssetDatabase.SaveAssets();
List<SearchResultGroup> searchResult = searchHandler.Run( m_searchParameters ).result;
if( searchResult != null )
SearchResult searchResult = searchHandler.Run( m_searchParameters );
if( !searchResult.success )
{
EditorUtility.DisplayDialog( "Error", "Couldn't refresh, check console for more info.", "OK" );
return;
}
List<SearchResultGroup> searchResultGroups = searchResult.result;
if( searchResultGroups != null )
{
int newSearchResultGroupIndex = -1;
for( int i = 0; i < searchResult.Count; i++ )
for( int i = 0; i < searchResultGroups.Count; i++ )
{
if( searchResultGroup.Title == searchResult[i].Title )
if( searchResultGroup.Title == searchResultGroups[i].Title )
{
newSearchResultGroupIndex = i;
break;
@@ -161,7 +178,7 @@ namespace AssetUsageDetectorNamespace
}
if( newSearchResultGroupIndex >= 0 )
result[searchResultGroupIndex] = searchResult[newSearchResultGroupIndex];
result[searchResultGroupIndex] = searchResultGroups[newSearchResultGroupIndex];
else
searchResultGroup.Clear();
}
@@ -179,10 +196,28 @@ namespace AssetUsageDetectorNamespace
{
parameters.searchResult = this;
parameters.tooltip = null;
parameters.guiRect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_0 );
float guiInitialY = parameters.guiRect.y;
for( int i = 0; i < result.Count; i++ )
{
result[i].DrawOnGUI( parameters );
if( i < result.Count - 1 )
{
Rect rect = parameters.guiRect;
rect.y += 10f;
parameters.guiRect = rect;
}
}
if( Event.current.type == EventType.Repaint )
guiHeight = parameters.guiRect.y - guiInitialY;
// To work nicely with GUILayout and scroll view
EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, GUILayout.Height( guiHeight ) );
if( parameters.tooltip != null )
{
// Show tooltip at mouse position
@@ -190,7 +225,26 @@ 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 )
{
parameters.shouldRefreshEditorWindow = false;
EditorWindow focusedWindow = EditorWindow.focusedWindow;
if( focusedWindow != null )
focusedWindow.Repaint();
EditorWindow mouseOverWindow = EditorWindow.mouseOverWindow;
if( mouseOverWindow != null && mouseOverWindow != focusedWindow )
mouseOverWindow.Repaint();
}
}
@@ -270,6 +324,16 @@ namespace AssetUsageDetectorNamespace
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
return false;
for( int i = 0; i < initialSceneSetup.Length; i++ )
{
Scene scene = EditorSceneManager.GetSceneByPath( initialSceneSetup[i].path );
if( !scene.isLoaded )
scene = EditorSceneManager.OpenScene( initialSceneSetup[i].path, initialSceneSetup[i].isLoaded ? OpenSceneMode.Additive : OpenSceneMode.AdditiveWithoutLoading );
if( initialSceneSetup[i].isActive )
EditorSceneManager.SetActiveScene( scene );
}
SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup();
for( int i = 0; i < sceneFinalSetup.Length; i++ )
{
@@ -365,6 +429,8 @@ namespace AssetUsageDetectorNamespace
}
}
private const float HEADER_HEIGHT = 40f;
public string Title { get; private set; }
public GroupType Type { get; private set; }
public bool IsExpanded { get; private set; }
@@ -374,6 +440,11 @@ namespace AssetUsageDetectorNamespace
private List<ReferencePath> referencePathsShortUnique;
private List<ReferencePath> referencePathsShortest;
private float calculatedGUIWidth;
private float calculatedGUIHeight;
private PathDrawingMode calculatedGUIMode;
private ReferenceNodeGUI[] guiNodes;
public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } }
@@ -387,6 +458,9 @@ namespace AssetUsageDetectorNamespace
references = new List<ReferenceNode>();
referencePathsShortUnique = null;
referencePathsShortest = null;
calculatedGUIWidth = 0f;
guiNodes = null;
}
// Add a reference to the list
@@ -404,6 +478,10 @@ namespace AssetUsageDetectorNamespace
referencePathsShortUnique.Clear();
if( referencePathsShortest != null )
referencePathsShortest.Clear();
PendingSearch = false;
calculatedGUIWidth = 0f;
guiNodes = null;
}
// Initializes commonly used variables of the nodes
@@ -422,10 +500,24 @@ namespace AssetUsageDetectorNamespace
}
}
for( int i = references.Count - 1; i >= 0; i-- )
{
references[i].VerifyLinksRecursively();
// Some links might be removed during verification
if( references[i].NumberOfOutgoingLinks == 0 )
references.RemoveAtFast( i );
}
if( references.Count == 0 )
return;
List<ReferenceNode> callStack = new List<ReferenceNode>( 8 );
// For simplicity's sake, get rid of root nodes that are already part of another node's hierarchy
for( int i = references.Count - 1; i >= 0; i-- )
{
if( IsRootNodePartOfAnotherRootNode( i ) )
if( IsRootNodePartOfAnotherRootNode( i, callStack ) )
references.RemoveAtFast( i );
}
@@ -443,6 +535,10 @@ namespace AssetUsageDetectorNamespace
if( mainAsset == null || mainAsset.Equals( null ) )
continue;
// We're already calling AssetDatabase.IsMainAsset but just in case...
if( ReferenceEquals( nodeObject, mainAsset ) )
continue;
if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset )
continue;
@@ -452,12 +548,12 @@ namespace AssetUsageDetectorNamespace
references[i] = newRootNode;
// Make sure that the new root node isn't already a part of another node's hierarchy
if( IsRootNodePartOfAnotherRootNode( i ) )
if( IsRootNodePartOfAnotherRootNode( i, callStack ) )
references.RemoveAtFast( i );
}
}
for( int i = references.Count - 1; i >= 0; i-- )
for( int i = 0; i < references.Count; i++ )
references[i].InitializeRecursively();
}
@@ -473,7 +569,7 @@ namespace AssetUsageDetectorNamespace
return false;
}
private bool IsRootNodePartOfAnotherRootNode( int index )
private bool IsRootNodePartOfAnotherRootNode( int index, List<ReferenceNode> callStack )
{
ReferenceNode node = references[index];
for( int i = references.Count - 1; i >= 0; i-- )
@@ -481,7 +577,7 @@ namespace AssetUsageDetectorNamespace
if( index == i )
continue;
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node ) )
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node, callStack ) )
return true;
}
@@ -565,15 +661,24 @@ namespace AssetUsageDetectorNamespace
// Draw the results found for this container
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
if( Event.current.type == EventType.Repaint && ( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode || parameters.guiRect.width != calculatedGUIWidth ) )
{
GenerateGUINodes( parameters );
parameters.shouldRefreshEditorWindow = true; // A repaint is needed to work nicely with GUILayout
}
Color c = GUI.color;
GUI.color = Color.cyan;
Rect rect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_40 );
Rect rect = parameters.guiRect;
float width = rect.width;
rect.width = 40f;
rect.height = HEADER_HEIGHT;
if( GUI.Button( rect, IsExpanded ? "v" : ">" ) )
{
IsExpanded = !IsExpanded;
parameters.shouldRefreshEditorWindow = true;
GUIUtility.ExitGUI();
}
@@ -581,8 +686,26 @@ namespace AssetUsageDetectorNamespace
rect.width = width - ( parameters.searchResult != null ? 140f : 40f );
if( GUI.Button( rect, Title, Utilities.BoxGUIStyle ) && Type == GroupType.Scene )
{
// If the container (scene, usually) is clicked, highlight it on Project view
AssetDatabase.LoadAssetAtPath<SceneAsset>( Title ).SelectInEditor();
if( Event.current.button != 1 )
{
// If the container (scene, usually) is left clicked, highlight it on Project view
AssetDatabase.LoadAssetAtPath<SceneAsset>( Title ).SelectInEditor();
}
else if( !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 )
{
// Show context menu when SearchResultGroup's header is right clicked
Scene scene = EditorSceneManager.GetSceneByPath( Title );
if( scene.isLoaded )
{
GenericMenu contextMenu = new GenericMenu();
contextMenu.AddItem( new GUIContent( "Close Scene" ), false, () =>
{
if( !scene.isDirty || EditorSceneManager.SaveModifiedScenesIfUserWantsTo( new Scene[1] { scene } ) )
EditorSceneManager.CloseScene( scene, true );
} );
contextMenu.ShowAsContext();
}
}
}
if( parameters.searchResult != null )
@@ -591,66 +714,110 @@ namespace AssetUsageDetectorNamespace
rect.width = 100f;
if( GUI.Button( rect, "Refresh" ) )
{
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
if( Utilities.AreScenesSaved() || ( EditorUtility.DisplayDialog( "Refresh", "Some scene(s) have unsaved changes, they must be saved before the refresh.", "Save Scenes", "Cancel" ) && EditorSceneManager.SaveOpenScenes() ) )
{
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
}
}
}
rect = parameters.guiRect;
rect.y += HEADER_HEIGHT + 5f;
if( IsExpanded )
{
GUI.color = Color.yellow;
if( PendingSearch )
GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
else if( references.Count == 0 )
GUILayout.Box( "No references found...", Utilities.BoxGUIStyle );
else
{
if( parameters.pathDrawingMode == PathDrawingMode.Full )
{
for( int i = 0; i < references.Count; i++ )
{
GUILayout.Space( 5 );
references[i].DrawOnGUIRecursively( parameters, null );
}
}
else
{
if( referencePathsShortUnique == null )
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
for( int i = 0; i < pathsToDraw.Count; i++ )
{
GUILayout.Space( 5 );
GUILayout.BeginHorizontal();
ReferencePath path = pathsToDraw[i];
path.startNode.DrawOnGUI( parameters, null );
ReferenceNode currentNode = path.startNode;
for( int j = 0; j < path.pathLinksToFollow.Length; j++ )
{
ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]];
link.targetNode.DrawOnGUI( parameters, link.description );
currentNode = link.targetNode;
}
GUILayout.EndHorizontal();
}
}
rect.height = 25f;
GUI.Box( rect, "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
}
else if( references.Count == 0 )
{
rect.height = 25f;
GUI.Box( rect, "No references found...", Utilities.BoxGUIStyle );
}
else if( guiNodes != null )
{
rect.height = calculatedGUIHeight;
parameters.guiRect = rect;
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i].DrawOnGUI( parameters );
}
rect.y += rect.height;
}
parameters.guiRect = rect;
GUI.color = c;
}
GUILayout.Space( 10 );
private void GenerateGUINodes( SearchResultDrawParameters parameters )
{
float guiRectWidth = parameters.guiRect.width;
if( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode )
{
if( parameters.pathDrawingMode == PathDrawingMode.Full )
{
List<ReferenceNode> stack = new List<ReferenceNode>( 8 );
guiNodes = new ReferenceNodeGUI[references.Count];
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i] = references[i].GenerateGUINodeRecursive( stack, null );
}
else
{
if( referencePathsShortUnique == null )
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
guiNodes = new ReferenceNodeGUI[pathsToDraw.Count];
for( int i = 0; i < guiNodes.Length; i++ )
{
ReferencePath path = pathsToDraw[i];
ReferenceNode currentNode = path.startNode;
ReferenceNodeGUI currentNodeGUI = currentNode.GenerateGUINode( null );
guiNodes[i] = currentNodeGUI;
for( int j = 0; j < path.pathLinksToFollow.Length; j++ )
{
ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]];
currentNodeGUI.links = new ReferenceNodeGUI[1] { link.targetNode.GenerateGUINode( link.description ) };
currentNode = link.targetNode;
currentNodeGUI = currentNodeGUI.links[0];
}
currentNodeGUI.links = new ReferenceNodeGUI[0];
}
}
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i].CalculateDepth();
}
calculatedGUIMode = parameters.pathDrawingMode;
calculatedGUIWidth = guiRectWidth;
calculatedGUIHeight = -5f; // will start from -5f + 5f = 0f
for( int i = 0; i < guiNodes.Length; i++ )
{
calculatedGUIHeight += 5f;
guiNodes[i].CalculateHeight( guiRectWidth );
guiNodes[i].CalculateOffset( new Vector2( 0f, calculatedGUIHeight ) );
calculatedGUIHeight += guiNodes[i].size.y;
}
}
// Serialize this result group
@@ -708,12 +875,12 @@ namespace AssetUsageDetectorNamespace
private static int uid_last = 0;
private readonly int uid;
public object nodeObject;
private readonly List<Link> links;
internal object nodeObject;
private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise
private string description; // String to print on this node
private readonly List<Link> links;
public Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } }
public int NumberOfOutgoingLinks { get { return links.Count; } }
@@ -725,11 +892,6 @@ namespace AssetUsageDetectorNamespace
uid = uid_last++;
}
public ReferenceNode( object obj ) : this()
{
nodeObject = obj;
}
// Add a one-way connection to another node
public void AddLinkTo( ReferenceNode nextNode, string description = null )
{
@@ -759,6 +921,40 @@ namespace AssetUsageDetectorNamespace
}
}
public void CopyReferencesTo( ReferenceNode other )
{
other.links.Clear();
other.links.AddRange( links );
}
// Remove any redundant connections that this node has
public void VerifyLinksRecursively()
{
// Make sure that this functions isn't called multiple times per node (avoids StackOverflowException)
if( description != null )
return;
description = "";
for( int i = links.Count - 1; i >= 0; i-- )
{
// Links from a GameObject to its components should be omitted if the component has no references (these are redundant links)
if( links[i].targetNode.links.Count == 0 && nodeObject is GameObject )
{
Component component = links[i].targetNode.nodeObject as Component;
if( component != null && !component.Equals( null ) && component.gameObject == (GameObject) nodeObject )
{
links.RemoveAtFast( i );
continue;
}
}
links[i].targetNode.VerifyLinksRecursively();
}
description = null;
}
// Initialize node's commonly used variables
public void InitializeRecursively()
{
@@ -789,20 +985,29 @@ namespace AssetUsageDetectorNamespace
}
// Returns whether or not specified node is part of this node's siblings
public bool NodeExistsInChildrenRecursive( ReferenceNode node )
public bool NodeExistsInChildrenRecursive( ReferenceNode node, List<ReferenceNode> callStack )
{
if( callStack.ContainsFast( this ) )
return false;
for( int i = 0; i < links.Count; i++ )
{
if( links[i].targetNode == node )
return true;
}
callStack.Add( this );
for( int i = 0; i < links.Count; i++ )
{
if( links[i].targetNode.NodeExistsInChildrenRecursive( node ) )
if( links[i].targetNode.NodeExistsInChildrenRecursive( node, callStack ) )
{
callStack.RemoveAt( callStack.Count - 1 );
return true;
}
}
callStack.RemoveAt( callStack.Count - 1 );
return false;
}
@@ -816,16 +1021,16 @@ namespace AssetUsageDetectorNamespace
// Calculate short unique paths that start with this node
public void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> currentPaths )
{
CalculateShortUniquePaths( currentPaths, new List<ReferenceNode>( 8 ), new List<int>( 8 ) { -1 }, 0 );
CalculateShortUniquePaths( currentPaths, new List<ReferenceNode>( 8 ), new List<int>( 8 ) { -1 }, 0, new List<ReferenceNode>( 8 ) );
}
// Just some boring calculations to find the short unique paths recursively
private void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> shortestPaths, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath )
private void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> shortestPaths, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath, List<ReferenceNode> stack )
{
int currentIndex = currentPath.Count;
currentPath.Add( this );
if( links.Count == 0 )
if( links.Count == 0 || stack.ContainsFast( this ) )
{
// Check if the path to the reference is unique (not discovered so far)
bool isUnique = true;
@@ -866,7 +1071,11 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < links.Count; i++ )
{
currentPathIndices.Add( i );
links[i].targetNode.CalculateShortUniquePaths( shortestPaths, currentPath, currentPathIndices, latestObjectIndexInPath );
stack.Add( this );
links[i].targetNode.CalculateShortUniquePaths( shortestPaths, currentPath, currentPathIndices, latestObjectIndexInPath, stack );
stack.RemoveAt( stack.Count - 1 );
currentPathIndices.RemoveAt( currentIndex + 1 );
}
}
@@ -874,41 +1083,33 @@ namespace AssetUsageDetectorNamespace
currentPath.RemoveAt( currentIndex );
}
// Draw all the paths that start with this node on GUI recursively
public void DrawOnGUIRecursively( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
public ReferenceNodeGUI GenerateGUINode( string linkToPrevNodeDescription )
{
GUILayout.BeginHorizontal();
DrawOnGUI( parameters, linkToPrevNodeDescription );
if( links.Count > 0 )
return new ReferenceNodeGUI()
{
GUILayout.BeginVertical();
for( int i = 0; i < links.Count; i++ )
{
ReferenceNode next = links[i].targetNode;
next.DrawOnGUIRecursively( parameters, links[i].description );
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
label = new GUIContent( string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ) ),
instanceId = instanceId
};
}
// Draw only this node on GUI
public void DrawOnGUI( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
public ReferenceNodeGUI GenerateGUINodeRecursive( List<ReferenceNode> stack, string linkToPrevNodeDescription )
{
string label = string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description );
if( GUILayout.Button( label, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_HEIGHT ) )
ReferenceNodeGUI guiNode = GenerateGUINode( linkToPrevNodeDescription );
if( stack.ContainsFast( this ) )
guiNode.links = new ReferenceNodeGUI[0];
else
{
// If a reference is clicked, highlight it (either on Hierarchy view or Project view)
UnityObject.SelectInEditor();
stack.Add( this );
guiNode.links = new ReferenceNodeGUI[links.Count];
for( int i = 0; i < links.Count; i++ )
guiNode.links[i] = links[i].targetNode.GenerateGUINodeRecursive( stack, links[i].description );
stack.RemoveAt( stack.Count - 1 );
}
if( parameters.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) )
parameters.tooltip = label;
return guiNode;
}
// Serialize this node and its connected nodes recursively
@@ -966,4 +1167,95 @@ namespace AssetUsageDetectorNamespace
return uid;
}
}
public class ReferenceNodeGUI
{
public GUIContent label;
public ReferenceNodeGUI[] links;
public int? instanceId;
private int depth;
private Vector2 offset;
public Vector2 size;
public void CalculateDepth()
{
depth = 0;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateDepth();
if( links[i].depth > depth )
depth = links[i].depth;
}
depth++;
}
public void CalculateHeight( float totalWidth )
{
size.x = totalWidth / depth;
totalWidth -= size.x;
size.y = Utilities.BoxGUIStyle.CalcHeight( label, size.x );
float connectedNodesHeight = 0f;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateHeight( totalWidth );
connectedNodesHeight += links[i].size.y;
}
if( size.y < connectedNodesHeight )
size.y = connectedNodesHeight;
else if( size.y > connectedNodesHeight )
ExpandHeightLeftToRight();
}
private void ExpandHeightLeftToRight()
{
float connectedNodesHeight = 0f;
for( int i = 0; i < links.Length; i++ )
connectedNodesHeight += links[i].size.y;
if( size.y > connectedNodesHeight )
{
for( int i = 0; i < links.Length; i++ )
{
links[i].size.y = size.y * links[i].size.y / connectedNodesHeight;
links[i].ExpandHeightLeftToRight();
}
}
}
public void CalculateOffset( Vector2 baseOffset )
{
offset = baseOffset;
baseOffset.x += size.x;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateOffset( baseOffset );
baseOffset.y += links[i].size.y;
}
}
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
Rect rect = parameters.guiRect;
rect.position += offset;
rect.size = size;
if( GUI.Button( rect, label, Utilities.BoxGUIStyle ) && instanceId.HasValue )
{
// If a reference is clicked, highlight it (either on Hierarchy view or Project view)
EditorUtility.InstanceIDToObject( instanceId.Value ).SelectInEditor();
}
for( int i = 0; i < links.Length; i++ )
links[i].DrawOnGUI( parameters );
if( parameters.showTooltips && Event.current.type == EventType.Repaint && rect.Contains( Event.current.mousePosition ) )
parameters.tooltip = label.text;
}
}
}
+29 -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
@@ -48,6 +56,7 @@ namespace AssetUsageDetectorNamespace.Extras
public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 );
public static readonly GUILayoutOption GL_WIDTH_100 = GUILayout.Width( 100 );
public static readonly GUILayoutOption GL_WIDTH_250 = GUILayout.Width( 250 );
public static readonly GUILayoutOption GL_HEIGHT_0 = GUILayout.Height( 0 );
public static readonly GUILayoutOption GL_HEIGHT_30 = GUILayout.Height( 30 );
public static readonly GUILayoutOption GL_HEIGHT_35 = GUILayout.Height( 35 );
public static readonly GUILayoutOption GL_HEIGHT_40 = GUILayout.Height( 40 );
@@ -350,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