Compare commits

..

2 Commits

4 changed files with 453 additions and 165 deletions
@@ -44,7 +44,7 @@ namespace AssetUsageDetectorNamespace
public bool searchInAssetsFolder = true; public bool searchInAssetsFolder = true;
public Object[] searchInAssetsSubset = null; public Object[] searchInAssetsSubset = null;
public Object[] excludedAssetsFromSearch = null; public Object[] excludedAssetsFromSearch = null;
public bool dontSearchInSourceAssets = false; public bool dontSearchInSourceAssets = true;
public Object[] excludedScenesFromSearch = null; public Object[] excludedScenesFromSearch = null;
public int searchDepthLimit = 4; public int searchDepthLimit = 4;
@@ -148,10 +148,12 @@ namespace AssetUsageDetectorNamespace
private int searchDepthLimit; // Depth limit for recursively searching variables of objects private int searchDepthLimit; // Depth limit for recursively searching variables of objects
private Object currentObject; private Object currentSearchedObject;
private int currentDepth; private int currentDepth;
private bool searchingSourceAssets;
private bool isInPlayMode; private bool isInPlayMode;
#if UNITY_2018_3_OR_NEWER #if UNITY_2018_3_OR_NEWER
private UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage; private UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage;
private GameObject openPrefabStagePrefabAsset; private GameObject openPrefabStagePrefabAsset;
@@ -302,7 +304,7 @@ namespace AssetUsageDetectorNamespace
if( obj.IsFolder() ) if( obj.IsFolder() )
folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) ); folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) );
else else
AddSearchedObjectToFilteredSets( obj ); AddSearchedObjectToFilteredSets( obj, true );
} }
foreach( string filePath in folderContentsSet ) foreach( string filePath in folderContentsSet )
@@ -316,7 +318,7 @@ namespace AssetUsageDetectorNamespace
continue; continue;
for( int i = 0; i < assets.Length; i++ ) for( int i = 0; i < assets.Length; i++ )
AddSearchedObjectToFilteredSets( assets[i] ); AddSearchedObjectToFilteredSets( assets[i], true );
} }
foreach( Object obj in objectsToSearchSet ) foreach( Object obj in objectsToSearchSet )
@@ -431,19 +433,7 @@ namespace AssetUsageDetectorNamespace
// Initialize the nodes of searched asset(s) // Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet ) foreach( Object obj in objectsToSearchSet )
{ searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) );
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 );
}
}
// Progressbar values // Progressbar values
int searchProgress = 0; int searchProgress = 0;
@@ -613,6 +603,20 @@ namespace AssetUsageDetectorNamespace
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
} }
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
if( !searchParameters.dontSearchInSourceAssets )
{
searchingSourceAssets = true;
foreach( Object obj in objectsToSearchSet )
{
currentSearchedObject = obj;
SearchObject( obj );
}
searchingSourceAssets = false;
}
InitializeSearchResultNodes( searchResult ); InitializeSearchResultNodes( searchResult );
// Log some c00l stuff to console // Log some c00l stuff to console
@@ -656,7 +660,7 @@ namespace AssetUsageDetectorNamespace
finally finally
{ {
currentSearchResultGroup = null; currentSearchResultGroup = null;
currentObject = null; currentSearchedObject = null;
EditorUtility.ClearProgressBar(); EditorUtility.ClearProgressBar();
@@ -682,7 +686,7 @@ namespace AssetUsageDetectorNamespace
} }
// Checks if object is asset or scene object and adds it to the corresponding HashSet(s) // 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 ) ) if( obj == null || obj.Equals( null ) )
return; return;
@@ -698,7 +702,7 @@ namespace AssetUsageDetectorNamespace
{ {
GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset ); GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset );
if( prefabStageObjectSource != null ) if( prefabStageObjectSource != null )
AddSearchedObjectToFilteredSets( prefabStageObjectSource ); AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects );
} }
#endif #endif
@@ -749,7 +753,7 @@ namespace AssetUsageDetectorNamespace
sceneObjectsToSearchScenesSet.Add( ( (Component) obj ).gameObject.scene.path ); 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 // If searched asset is a GameObject, include its components in the search
Component[] components = ( (GameObject) obj ).GetComponents<Component>(); Component[] components = ( (GameObject) obj ).GetComponents<Component>();
@@ -766,6 +770,11 @@ namespace AssetUsageDetectorNamespace
sceneObjectsToSearchSet.Add( components[i] ); 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 // Search a scene for references
@@ -846,10 +855,10 @@ namespace AssetUsageDetectorNamespace
if( obj is SceneAsset ) if( obj is SceneAsset )
return; return;
currentObject = obj; currentSearchedObject = obj;
ReferenceNode searchResult = SearchObject( obj ); ReferenceNode searchResult = SearchObject( obj );
if( searchResult != null && currentSearchResultGroup != null ) if( searchResult != null )
currentSearchResultGroup.AddReference( searchResult ); currentSearchResultGroup.AddReference( searchResult );
} }
@@ -863,16 +872,21 @@ namespace AssetUsageDetectorNamespace
if( callStack.ContainsFast( obj ) ) if( callStack.ContainsFast( obj ) )
return null; 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 // Hashing does not work well with structs all the time, don't cache search results for structs
string objHash = null; string objHash = null;
if( !( obj is ValueType ) ) if( !( obj is ValueType ) )
{ {
objHash = obj.Hash(); objHash = obj.Hash();
// If object was searched before, return the cached result if( !searchingSourceAsset )
ReferenceNode cachedResult; {
if( searchedObjects.TryGetValue( objHash, out cachedResult ) ) // If object was searched before, return the cached result
return cachedResult; ReferenceNode cachedResult;
if( searchedObjects.TryGetValue( objHash, out cachedResult ) )
return cachedResult;
}
} }
searchedObjectsCount++; searchedObjectsCount++;
@@ -881,21 +895,6 @@ namespace AssetUsageDetectorNamespace
Object unityObject = obj as Object; Object unityObject = obj as Object;
if( unityObject != null ) 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 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 ) ) ) ) if( unityObject.IsAsset() && ( assetsToSearchSet.Count == 0 || !AssetHasAnyReference( AssetDatabase.GetAssetPath( unityObject ) ) ) )
{ {
@@ -945,7 +944,15 @@ namespace AssetUsageDetectorNamespace
// and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something // 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) // or we are at the root of the search; i.e. currentDepth == 0)
if( objHash != null && ( result != null || unityObject != null || 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; return result;
} }
@@ -1253,12 +1260,13 @@ namespace AssetUsageDetectorNamespace
break; break;
} }
if( searchResult != null ) if( searchResult != null && searchResult != referenceNode )
{ {
if( searchResult != referenceNode ) string propertyPath = iterator.propertyPath;
referenceNode.AddLinkTo( searchResult, "Variable: " + iterator.propertyPath );
else // m_RD.texture is a redundant reference that shows up when searching sprites
PoolReferenceNode( searchResult ); if( !propertyPath.EndsWith( "m_RD.texture", StringComparison.Ordinal ) )
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath );
} }
} while( iterator.NextVisible( enterChildren ) ); } while( iterator.NextVisible( enterChildren ) );
@@ -1292,29 +1300,22 @@ namespace AssetUsageDetectorNamespace
if( !( variableValue is ICollection ) ) if( !( variableValue is ICollection ) )
{ {
ReferenceNode searchResult = SearchObject( variableValue ); ReferenceNode searchResult = SearchObject( variableValue );
if( searchResult != null ) if( searchResult != null && searchResult != referenceNode )
{ referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
if( searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
else
PoolReferenceNode( searchResult );
}
} }
if( variableValue is IEnumerable && !( variableValue is Transform ) ) if( variableValue is IEnumerable && !( variableValue is Transform ) )
{ {
// If the field is IEnumerable (possibly an array or collection), search through members of it // If the field is IEnumerable (possibly an array or collection), search through members of it
// Note that Transform IEnumerable (children of the transform) is not iterated // Note that Transform IEnumerable (children of the transform) is not iterated
int index = 0;
foreach( object element in (IEnumerable) variableValue ) foreach( object element in (IEnumerable) variableValue )
{ {
ReferenceNode searchResult = SearchObject( element ); ReferenceNode searchResult = SearchObject( element );
if( searchResult != null ) if( searchResult != null && searchResult != referenceNode )
{ referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) );
if( searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property (IEnumerable): " : "Variable (IEnumerable): " ) + variables[i].name ); index++;
else
PoolReferenceNode( searchResult );
}
} }
} }
} }
@@ -232,7 +232,7 @@ namespace AssetUsageDetectorNamespace.Extras
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) ); ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true ); 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 ); searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
// Fetch public, protected and private non-static fields and properties from objects by default // Fetch public, protected and private non-static fields and properties from objects by default
@@ -514,7 +514,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 ); 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; searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full;
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
+387 -101
View File
@@ -4,6 +4,7 @@ using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement; using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
@@ -15,6 +16,8 @@ namespace AssetUsageDetectorNamespace
public PathDrawingMode pathDrawingMode; public PathDrawingMode pathDrawingMode;
public bool showTooltips; public bool showTooltips;
public bool noAssetDatabaseChanges; public bool noAssetDatabaseChanges;
public Rect guiRect;
public bool shouldRefreshEditorWindow;
public string tooltip; public string tooltip;
public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips, bool noAssetDatabaseChanges ) public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips, bool noAssetDatabaseChanges )
@@ -52,13 +55,20 @@ namespace AssetUsageDetectorNamespace
public List<string> linkDescriptions; 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 List<SearchResultGroup> result;
private SceneSetup[] initialSceneSetup; private SceneSetup[] initialSceneSetup;
private AssetUsageDetector searchHandler; private AssetUsageDetector searchHandler;
private AssetUsageDetector.Parameters m_searchParameters; 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<SerializableNode> serializedNodes;
private List<SerializableResultGroup> serializedGroups; private List<SerializableResultGroup> serializedGroups;
@@ -147,13 +157,20 @@ namespace AssetUsageDetectorNamespace
// Make sure the AssetDatabase is up-to-date // Make sure the AssetDatabase is up-to-date
AssetDatabase.SaveAssets(); AssetDatabase.SaveAssets();
List<SearchResultGroup> searchResult = searchHandler.Run( m_searchParameters ).result; SearchResult searchResult = searchHandler.Run( m_searchParameters );
if( searchResult != null ) 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; 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; newSearchResultGroupIndex = i;
break; break;
@@ -161,7 +178,7 @@ namespace AssetUsageDetectorNamespace
} }
if( newSearchResultGroupIndex >= 0 ) if( newSearchResultGroupIndex >= 0 )
result[searchResultGroupIndex] = searchResult[newSearchResultGroupIndex]; result[searchResultGroupIndex] = searchResultGroups[newSearchResultGroupIndex];
else else
searchResultGroup.Clear(); searchResultGroup.Clear();
} }
@@ -179,10 +196,28 @@ namespace AssetUsageDetectorNamespace
{ {
parameters.searchResult = this; parameters.searchResult = this;
parameters.tooltip = null; 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++ ) for( int i = 0; i < result.Count; i++ )
{
result[i].DrawOnGUI( parameters ); 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 ) if( parameters.tooltip != null )
{ {
// Show tooltip at mouse position // Show tooltip at mouse position
@@ -192,6 +227,19 @@ namespace AssetUsageDetectorNamespace
GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), parameters.tooltip, Utilities.TooltipGUIStyle ); GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), 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();
}
} }
public Object[] SelectAllAsObjects() public Object[] SelectAllAsObjects()
@@ -270,6 +318,16 @@ namespace AssetUsageDetectorNamespace
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() ) if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
return false; 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(); SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup();
for( int i = 0; i < sceneFinalSetup.Length; i++ ) for( int i = 0; i < sceneFinalSetup.Length; i++ )
{ {
@@ -365,6 +423,8 @@ namespace AssetUsageDetectorNamespace
} }
} }
private const float HEADER_HEIGHT = 40f;
public string Title { get; private set; } public string Title { get; private set; }
public GroupType Type { get; private set; } public GroupType Type { get; private set; }
public bool IsExpanded { get; private set; } public bool IsExpanded { get; private set; }
@@ -374,6 +434,11 @@ namespace AssetUsageDetectorNamespace
private List<ReferencePath> referencePathsShortUnique; private List<ReferencePath> referencePathsShortUnique;
private List<ReferencePath> referencePathsShortest; private List<ReferencePath> referencePathsShortest;
private float calculatedGUIWidth;
private float calculatedGUIHeight;
private PathDrawingMode calculatedGUIMode;
private ReferenceNodeGUI[] guiNodes;
public int NumberOfReferences { get { return references.Count; } } public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } } public ReferenceNode this[int index] { get { return references[index]; } }
@@ -387,6 +452,9 @@ namespace AssetUsageDetectorNamespace
references = new List<ReferenceNode>(); references = new List<ReferenceNode>();
referencePathsShortUnique = null; referencePathsShortUnique = null;
referencePathsShortest = null; referencePathsShortest = null;
calculatedGUIWidth = 0f;
guiNodes = null;
} }
// Add a reference to the list // Add a reference to the list
@@ -404,6 +472,10 @@ namespace AssetUsageDetectorNamespace
referencePathsShortUnique.Clear(); referencePathsShortUnique.Clear();
if( referencePathsShortest != null ) if( referencePathsShortest != null )
referencePathsShortest.Clear(); referencePathsShortest.Clear();
PendingSearch = false;
calculatedGUIWidth = 0f;
guiNodes = null;
} }
// Initializes commonly used variables of the nodes // Initializes commonly used variables of the nodes
@@ -422,10 +494,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 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-- ) for( int i = references.Count - 1; i >= 0; i-- )
{ {
if( IsRootNodePartOfAnotherRootNode( i ) ) if( IsRootNodePartOfAnotherRootNode( i, callStack ) )
references.RemoveAtFast( i ); references.RemoveAtFast( i );
} }
@@ -443,6 +529,10 @@ namespace AssetUsageDetectorNamespace
if( mainAsset == null || mainAsset.Equals( null ) ) if( mainAsset == null || mainAsset.Equals( null ) )
continue; continue;
// We're already calling AssetDatabase.IsMainAsset but just in case...
if( ReferenceEquals( nodeObject, mainAsset ) )
continue;
if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset ) if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset )
continue; continue;
@@ -452,12 +542,12 @@ namespace AssetUsageDetectorNamespace
references[i] = newRootNode; references[i] = newRootNode;
// Make sure that the new root node isn't already a part of another node's hierarchy // 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 ); references.RemoveAtFast( i );
} }
} }
for( int i = references.Count - 1; i >= 0; i-- ) for( int i = 0; i < references.Count; i++ )
references[i].InitializeRecursively(); references[i].InitializeRecursively();
} }
@@ -473,7 +563,7 @@ namespace AssetUsageDetectorNamespace
return false; return false;
} }
private bool IsRootNodePartOfAnotherRootNode( int index ) private bool IsRootNodePartOfAnotherRootNode( int index, List<ReferenceNode> callStack )
{ {
ReferenceNode node = references[index]; ReferenceNode node = references[index];
for( int i = references.Count - 1; i >= 0; i-- ) for( int i = references.Count - 1; i >= 0; i-- )
@@ -481,7 +571,7 @@ namespace AssetUsageDetectorNamespace
if( index == i ) if( index == i )
continue; continue;
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node ) ) if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node, callStack ) )
return true; return true;
} }
@@ -565,15 +655,24 @@ namespace AssetUsageDetectorNamespace
// Draw the results found for this container // Draw the results found for this container
public void DrawOnGUI( SearchResultDrawParameters parameters ) 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; Color c = GUI.color;
GUI.color = Color.cyan; GUI.color = Color.cyan;
Rect rect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_40 ); Rect rect = parameters.guiRect;
float width = rect.width; float width = rect.width;
rect.width = 40f; rect.width = 40f;
rect.height = HEADER_HEIGHT;
if( GUI.Button( rect, IsExpanded ? "v" : ">" ) ) if( GUI.Button( rect, IsExpanded ? "v" : ">" ) )
{ {
IsExpanded = !IsExpanded; IsExpanded = !IsExpanded;
parameters.shouldRefreshEditorWindow = true;
GUIUtility.ExitGUI(); GUIUtility.ExitGUI();
} }
@@ -581,8 +680,26 @@ namespace AssetUsageDetectorNamespace
rect.width = width - ( parameters.searchResult != null ? 140f : 40f ); rect.width = width - ( parameters.searchResult != null ? 140f : 40f );
if( GUI.Button( rect, Title, Utilities.BoxGUIStyle ) && Type == GroupType.Scene ) if( GUI.Button( rect, Title, Utilities.BoxGUIStyle ) && Type == GroupType.Scene )
{ {
// If the container (scene, usually) is clicked, highlight it on Project view if( Event.current.button != 1 )
AssetDatabase.LoadAssetAtPath<SceneAsset>( Title ).SelectInEditor(); {
// 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 ) if( parameters.searchResult != null )
@@ -591,66 +708,110 @@ namespace AssetUsageDetectorNamespace
rect.width = 100f; rect.width = 100f;
if( GUI.Button( rect, "Refresh" ) ) if( GUI.Button( rect, "Refresh" ) )
{ {
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges ); if( Utilities.AreScenesSaved() || ( EditorUtility.DisplayDialog( "Refresh", "Some scene(s) have unsaved changes, they must be saved before the refresh.", "Save Scenes", "Cancel" ) && EditorSceneManager.SaveOpenScenes() ) )
GUIUtility.ExitGUI(); {
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
}
} }
} }
rect = parameters.guiRect;
rect.y += HEADER_HEIGHT + 5f;
if( IsExpanded ) if( IsExpanded )
{ {
GUI.color = Color.yellow; GUI.color = Color.yellow;
if( PendingSearch ) 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 ) rect.height = 25f;
{ GUI.Box( rect, "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
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();
}
}
} }
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; 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 // Serialize this result group
@@ -708,12 +869,12 @@ namespace AssetUsageDetectorNamespace
private static int uid_last = 0; private static int uid_last = 0;
private readonly int uid; private readonly int uid;
public object nodeObject; internal object nodeObject;
private readonly List<Link> links;
private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise 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 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 Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } }
public int NumberOfOutgoingLinks { get { return links.Count; } } public int NumberOfOutgoingLinks { get { return links.Count; } }
@@ -725,11 +886,6 @@ namespace AssetUsageDetectorNamespace
uid = uid_last++; uid = uid_last++;
} }
public ReferenceNode( object obj ) : this()
{
nodeObject = obj;
}
// Add a one-way connection to another node // Add a one-way connection to another node
public void AddLinkTo( ReferenceNode nextNode, string description = null ) public void AddLinkTo( ReferenceNode nextNode, string description = null )
{ {
@@ -759,6 +915,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 // Initialize node's commonly used variables
public void InitializeRecursively() public void InitializeRecursively()
{ {
@@ -789,20 +979,29 @@ namespace AssetUsageDetectorNamespace
} }
// Returns whether or not specified node is part of this node's siblings // 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++ ) for( int i = 0; i < links.Count; i++ )
{ {
if( links[i].targetNode == node ) if( links[i].targetNode == node )
return true; return true;
} }
callStack.Add( this );
for( int i = 0; i < links.Count; i++ ) 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; return true;
}
} }
callStack.RemoveAt( callStack.Count - 1 );
return false; return false;
} }
@@ -816,16 +1015,16 @@ namespace AssetUsageDetectorNamespace
// Calculate short unique paths that start with this node // Calculate short unique paths that start with this node
public void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> currentPaths ) 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 // 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; int currentIndex = currentPath.Count;
currentPath.Add( this ); 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) // Check if the path to the reference is unique (not discovered so far)
bool isUnique = true; bool isUnique = true;
@@ -866,7 +1065,11 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < links.Count; i++ ) for( int i = 0; i < links.Count; i++ )
{ {
currentPathIndices.Add( 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 ); currentPathIndices.RemoveAt( currentIndex + 1 );
} }
} }
@@ -874,41 +1077,33 @@ namespace AssetUsageDetectorNamespace
currentPath.RemoveAt( currentIndex ); currentPath.RemoveAt( currentIndex );
} }
// Draw all the paths that start with this node on GUI recursively public ReferenceNodeGUI GenerateGUINode( string linkToPrevNodeDescription )
public void DrawOnGUIRecursively( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
{ {
GUILayout.BeginHorizontal(); return new ReferenceNodeGUI()
DrawOnGUI( parameters, linkToPrevNodeDescription );
if( links.Count > 0 )
{ {
GUILayout.BeginVertical(); label = new GUIContent( string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ) ),
instanceId = instanceId
for( int i = 0; i < links.Count; i++ ) };
{
ReferenceNode next = links[i].targetNode;
next.DrawOnGUIRecursively( parameters, links[i].description );
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
} }
// Draw only this node on GUI public ReferenceNodeGUI GenerateGUINodeRecursive( List<ReferenceNode> stack, string linkToPrevNodeDescription )
public void DrawOnGUI( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
{ {
string label = string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ); ReferenceNodeGUI guiNode = GenerateGUINode( linkToPrevNodeDescription );
if( GUILayout.Button( label, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_HEIGHT ) )
if( stack.ContainsFast( this ) )
guiNode.links = new ReferenceNodeGUI[0];
else
{ {
// If a reference is clicked, highlight it (either on Hierarchy view or Project view) stack.Add( this );
UnityObject.SelectInEditor();
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 ) ) return guiNode;
parameters.tooltip = label;
} }
// Serialize this node and its connected nodes recursively // Serialize this node and its connected nodes recursively
@@ -966,4 +1161,95 @@ namespace AssetUsageDetectorNamespace
return uid; 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;
}
}
} }
@@ -48,6 +48,7 @@ namespace AssetUsageDetectorNamespace.Extras
public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 ); 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_100 = GUILayout.Width( 100 );
public static readonly GUILayoutOption GL_WIDTH_250 = GUILayout.Width( 250 ); 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_30 = GUILayout.Height( 30 );
public static readonly GUILayoutOption GL_HEIGHT_35 = GUILayout.Height( 35 ); public static readonly GUILayoutOption GL_HEIGHT_35 = GUILayout.Height( 35 );
public static readonly GUILayoutOption GL_HEIGHT_40 = GUILayout.Height( 40 ); public static readonly GUILayoutOption GL_HEIGHT_40 = GUILayout.Height( 40 );