diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs index bfea32c..47fed7d 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs @@ -8,18 +8,32 @@ using System.Collections; using System.Collections.Generic; using System.Reflection; using System; -using Object = UnityEngine.Object; using System.Runtime.Serialization.Formatters.Binary; using System.IO; +using Object = UnityEngine.Object; namespace AssetUsageDetectorNamespace { - public enum Phase { Setup, Processing, Complete }; - public enum PathDrawingMode { Full, ShortRelevantParts, Shortest }; + [Flags] + public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 }; - public class AssetUsageDetector : EditorWindow + public class AssetUsageDetector { #region Helper Classes + public class Parameters + { + public IEnumerable objectsToSearch; + + public SceneSearchMode searchInScenes; + public bool searchInAssetsFolder; + public IEnumerable searchInAssetsSubset; + + public int searchDepthLimit; + public BindingFlags fieldModifiers, propertyModifiers; + + public bool noAssetDatabaseChanges; + } + [Serializable] private class CacheEntry { @@ -66,11 +80,8 @@ namespace AssetUsageDetectorNamespace } #endregion - private const float PLAY_MODE_REFRESH_INTERVAL = 1f; // Interval to refresh the editor window in play mode private const string DEPENDENCY_CACHE_PATH = "Library/AssetUsageDetector.cache"; // Path of the cache file - private List objectsToSearch = new List() { new ObjectToSearch( null ) }; - private HashSet objectsToSearchSet; // A set that contains the searched asset(s) and their sub-assets (if any) private HashSet sceneObjectsToSearchSet; // Scene object(s) in objectsToSearchSet @@ -79,11 +90,7 @@ namespace AssetUsageDetectorNamespace private HashSet assetsToSearchSet; // Project asset(s) in objectsToSearchSet private HashSet assetsToSearchPathsSet; // objectsToSearchSet's path(s) - private Phase currentPhase = Phase.Setup; - private PathDrawingMode pathDrawingMode = PathDrawingMode.ShortRelevantParts; - - private List searchResult = new List(); // Overall search results - private ReferenceHolder currentReferenceHolder; // Results for the currently searched scene + private SearchResultGroup currentSearchResultGroup; // Results for the currently searched scene private Dictionary typeToVariables; // An optimization to fetch & filter fields and properties of a class only once private Dictionary searchedObjects; // An optimization to search an object only once (key is a hash of the searched object) @@ -99,822 +106,284 @@ namespace AssetUsageDetectorNamespace private bool searchSerializableVariablesOnly; - private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view - private bool searchInScenesInBuild = true; // Scenes in build - private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not) - private bool searchInAllScenes = true; // All scenes (including scenes that are not in build) - private bool searchInAssetsFolder = true; // Assets in Project view + private int searchDepthLimit; // Depth limit for recursively searching variables of objects - private List searchInAssets = new List() { null }; // If not empty, only these assets are searched for references + private int currentDepth; - private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects - private int currentDepth = 0; + private BindingFlags fieldModifiers, propertyModifiers; + private BindingFlags prevFieldModifiers, prevPropertyModifiers; - private bool restoreInitialSceneSetup = true; // Close the additively loaded scenes that were not part of the initial scene setup - private SceneSetup[] initialSceneSetup; // Initial scene setup (which scenes were open and/or loaded) - - private string errorMessage = string.Empty; - - // Fetch public, protected and private non-static fields and properties from objects by default - private BindingFlags fieldModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic; - private BindingFlags propertyModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic; - - private int prevSearchDepthLimit; - private BindingFlags prevFieldModifiers; - private BindingFlags prevPropertyModifiers; - - public static string tooltip = null; - public static bool showTooltips = false; - - private double nextPlayModeRefreshTime = 0f; - - private Vector2 scrollPosition = Vector2.zero; - - private int searchCount; // Number of searched objects + private int searchedObjectsCount; // Number of searched objects private double searchStartTime; private List nodesPool = new List( 32 ); private List validVariables = new List( 32 ); - // Add "Asset Usage Detector" menu item to the Window menu - [MenuItem( "Window/Asset Usage Detector" )] - private static void Init() + // Search for references! + public SearchResult Run( Parameters searchParameters ) { - AssetUsageDetector window = GetWindow(); - window.titleContent = new GUIContent( "Asset Usage Detector" ); - window.minSize = new Vector2( 325f, 220f ); - window.Show(); - } - - private void OnDisable() - { - SaveCache(); - } - - private void OnDestroy() - { - if( currentPhase == Phase.Complete && !EditorApplication.isPlaying && initialSceneSetup != null ) + if( searchParameters.objectsToSearch == null ) { - if( EditorUtility.DisplayDialog( "Scenes", "Restore initial scene setup?", "Yes", "Leave it as is" ) ) - RestoreInitialSceneSetup(); + Debug.LogError( "objectsToSearch list is empty" ); + return new SearchResult( null, null ); } - } - private void Update() - { - // Refresh the window at a regular interval in play mode to update the tooltip - if( EditorApplication.isPlaying && currentPhase == Phase.Complete && showTooltips && EditorApplication.timeSinceStartup >= nextPlayModeRefreshTime ) + // Get the scenes that are open right now + SceneSetup[] initialSceneSetup = !EditorApplication.isPlaying ? EditorSceneManager.GetSceneManagerSetup() : null; + + try { - nextPlayModeRefreshTime = EditorApplication.timeSinceStartup + PLAY_MODE_REFRESH_INTERVAL; ; - Repaint(); - } - } + currentDepth = 0; + searchedObjectsCount = 0; + searchStartTime = EditorApplication.timeSinceStartup; - private void OnGUI() - { - // Make the window scrollable - scrollPosition = EditorGUILayout.BeginScrollView( scrollPosition, Utilities.GL_EXPAND_WIDTH, Utilities.GL_EXPAND_HEIGHT ); + this.fieldModifiers = searchParameters.fieldModifiers; + this.propertyModifiers = searchParameters.propertyModifiers; + this.searchDepthLimit = searchParameters.searchDepthLimit; - GUILayout.BeginVertical(); + // Initialize commonly used variables + List searchResult = new List(); // Overall search results - GUILayout.Space( 10 ); + if( typeToVariables == null ) + typeToVariables = new Dictionary( 4096 ); + else if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers ) + typeToVariables.Clear(); - // Show the error message, if it is not empty - if( errorMessage.Length > 0 ) - EditorGUILayout.HelpBox( errorMessage, MessageType.Error ); + if( searchedObjects == null ) + searchedObjects = new Dictionary( 32768 ); + else + searchedObjects.Clear(); - GUILayout.Space( 10 ); + if( callStack == null ) + callStack = new Stack( 64 ); + else + callStack.Clear(); - if( currentPhase == Phase.Processing ) - { - // If we are stuck at this phase, then we have encountered an exception - GUILayout.Label( ". . . Something went wrong, check console . . ." ); + if( objectsToSearchSet == null ) + objectsToSearchSet = new HashSet(); + else + objectsToSearchSet.Clear(); - restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup (Recommended)", restoreInitialSceneSetup ); + if( sceneObjectsToSearchSet == null ) + sceneObjectsToSearchSet = new HashSet(); + else + sceneObjectsToSearchSet.Clear(); - if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) ) + if( sceneObjectsToSearchScenesSet == null ) + sceneObjectsToSearchScenesSet = new HashSet(); + else + sceneObjectsToSearchScenesSet.Clear(); + + if( assetsToSearchSet == null ) + assetsToSearchSet = new HashSet(); + else + assetsToSearchSet.Clear(); + + if( assetsToSearchPathsSet == null ) + assetsToSearchPathsSet = new HashSet(); + else + assetsToSearchPathsSet.Clear(); + + if( assetDependencyCache == null ) { - if( !restoreInitialSceneSetup || RestoreInitialSceneSetup() ) + LoadCache(); + searchStartTime = EditorApplication.timeSinceStartup; + } + else if( !searchParameters.noAssetDatabaseChanges ) + { + foreach( var cacheEntry in assetDependencyCache.Values ) + cacheEntry.verified = false; + } + + prevFieldModifiers = fieldModifiers; + prevPropertyModifiers = propertyModifiers; + + searchPrefabConnections = false; + searchMonoBehavioursForScript = false; + searchRenderers = false; + searchMaterialsForShader = false; + searchMaterialsForTexture = false; + + // Store the searched objects(s) in HashSets + HashSet folderContentsSet = new HashSet(); + foreach( Object obj in searchParameters.objectsToSearch ) + { + if( obj == null || obj.Equals( null ) ) + continue; + + if( obj.IsFolder() ) + folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) ); + else + AddSearchedObjectToFilteredSets( obj ); + } + + foreach( string filePath in folderContentsSet ) + { + Object[] assets = AssetDatabase.LoadAllAssetsAtPath( filePath ); + if( assets == null || assets.Length == 0 ) + continue; + + for( int i = 0; i < assets.Length; i++ ) + AddSearchedObjectToFilteredSets( assets[i] ); + } + + foreach( Object obj in objectsToSearchSet ) + { + // Initialize the nodes of searched asset(s) + searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) ); + + if( obj is Texture ) { - errorMessage = string.Empty; - currentPhase = Phase.Setup; + searchRenderers = true; + searchMaterialsForTexture = true; + } + else if( obj is Material ) + { + searchRenderers = true; + } + else if( obj is MonoScript ) + { + searchMonoBehavioursForScript = true; + } + else if( obj is Shader ) + { + searchRenderers = true; + searchMaterialsForShader = true; + } + else if( obj is GameObject ) + { + searchPrefabConnections = true; } } - } - else if( currentPhase == Phase.Setup ) - { - if( ExposeSearchedObjects() ) - errorMessage = string.Empty; - - GUILayout.Space( 10 ); - - GUILayout.Box( "SEARCH IN", Utilities.GL_EXPAND_WIDTH ); - - searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project view (Assets folder)", searchInAssetsFolder ); - - if( searchInAssetsFolder ) - { - GUILayout.BeginHorizontal(); - GUILayout.Space( 35 ); - GUILayout.BeginVertical(); - - ExposeAssetsToSearch(); - - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - } - - GUILayout.Space( 10 ); + // Find the scenes to search for references if( EditorApplication.isPlaying ) + searchParameters.searchInScenes = ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes ? SceneSearchMode.OpenScenes : SceneSearchMode.None; + + HashSet scenesToSearch = new HashSet(); + if( ( searchParameters.searchInScenes & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes ) { - searchInAllScenes = false; - searchInScenesInBuild = false; + // Get all scenes from the Assets folder + string[] sceneGuids = AssetDatabase.FindAssets( "t:SceneAsset" ); + for( int i = 0; i < sceneGuids.Length; i++ ) + scenesToSearch.Add( AssetDatabase.GUIDToAssetPath( sceneGuids[i] ) ); } - else if( searchInAllScenes ) - GUI.enabled = false; - - searchInOpenScenes = EditorGUILayout.ToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes ); - - if( EditorApplication.isPlaying ) - GUI.enabled = false; - - searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", searchInScenesInBuild ); - - if( searchInScenesInBuild ) + else { - GUILayout.BeginHorizontal(); - GUILayout.Space( 35 ); + if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes ) + { + // Get all open (and loaded) scenes + for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) + { + Scene scene = EditorSceneManager.GetSceneAt( i ); + if( scene.IsValid() ) + scenesToSearch.Add( scene.path ); + } + } - searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); - searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); - - GUILayout.EndHorizontal(); + bool searchInScenesInBuildTickedAll = ( searchParameters.searchInScenes & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll; + if( searchInScenesInBuildTickedAll || ( searchParameters.searchInScenes & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly ) + { + // Get all scenes in build settings + EditorBuildSettingsScene[] scenesTemp = EditorBuildSettings.scenes; + for( int i = 0; i < scenesTemp.Length; i++ ) + { + if( searchInScenesInBuildTickedAll || scenesTemp[i].enabled ) + scenesToSearch.Add( scenesTemp[i].path ); + } + } } - if( !EditorApplication.isPlaying ) - GUI.enabled = true; + // By default, search only serializable variables for references + searchSerializableVariablesOnly = true; - searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes ); - - GUI.enabled = true; - - GUILayout.Space( 10 ); - - GUILayout.Box( "SEARCH SETTINGS", Utilities.GL_EXPAND_WIDTH ); - - GUILayout.BeginHorizontal(); - - GUILayout.Label( new GUIContent( "> Search depth: " + searchDepthLimit, "Depth limit for recursively searching variables of objects" ), Utilities.GL_WIDTH_250 ); - - searchDepthLimit = (int) GUILayout.HorizontalSlider( searchDepthLimit, 0, 4 ); - - GUILayout.EndHorizontal(); - - GUILayout.Label( "> Search variables:" ); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Public", ( fieldModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) - fieldModifiers |= BindingFlags.Public; - else - fieldModifiers &= ~BindingFlags.Public; - - if( EditorGUILayout.ToggleLeft( "Non-public", ( fieldModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) - fieldModifiers |= BindingFlags.NonPublic; - else - fieldModifiers &= ~BindingFlags.NonPublic; - - GUILayout.EndHorizontal(); - - GUILayout.Label( "> Search properties (can be slow):" ); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Public", ( propertyModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) - propertyModifiers |= BindingFlags.Public; - else - propertyModifiers &= ~BindingFlags.Public; - - if( EditorGUILayout.ToggleLeft( "Non-public", ( propertyModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) - propertyModifiers |= BindingFlags.NonPublic; - else - propertyModifiers &= ~BindingFlags.NonPublic; - - GUILayout.EndHorizontal(); - - GUILayout.Space( 10 ); - - // Don't let the user press the GO button without any valid search location - if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder ) - GUI.enabled = false; - - if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) ) + // Don't search assets if searched object(s) are all scene objects as assets can't hold references to scene objects + if( searchParameters.searchInAssetsFolder && assetsToSearchSet.Count > 0 ) { - if( AreSearchedObjectsEmpty() ) - { - errorMessage = "ADD AN ASSET TO THE LIST FIRST!"; - } - else if( !EditorApplication.isPlaying && !AreScenesSaved() ) - { - // Don't start the search if at least one scene is currently dirty (not saved) - errorMessage = "SAVE OPEN SCENES FIRST!"; - } + currentSearchResultGroup = new SearchResultGroup( "Project View (Assets)", false ); + + // Get the paths of all assets that are to be searched + IEnumerable assetPaths; + if( searchParameters.searchInAssetsSubset == null ) + assetPaths = AssetDatabase.GetAllAssetPaths(); else { - errorMessage = string.Empty; - currentPhase = Phase.Processing; + folderContentsSet.Clear(); - if( !EditorApplication.isPlaying ) - initialSceneSetup = EditorSceneManager.GetSceneManagerSetup(); // Get the scenes that are open right now - else - initialSceneSetup = null; - - // Start searching - ExecuteQuery(); - } - } - } - else if( currentPhase == Phase.Complete ) - { - // Draw the results of the search - GUI.enabled = false; - - ExposeSearchedObjects(); - - GUILayout.Space( 10 ); - GUI.enabled = true; - - restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup after search is reset (Recommended)", restoreInitialSceneSetup ); - - if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) ) - { - if( !restoreInitialSceneSetup || RestoreInitialSceneSetup() ) - { - errorMessage = string.Empty; - currentPhase = Phase.Setup; - - if( searchResult != null ) - searchResult.Clear(); - } - } - - Color c = GUI.color; - GUI.color = Color.green; - GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.GL_EXPAND_WIDTH ); - GUI.color = c; - - GUILayout.Space( 10 ); - - if( searchResult.Count == 0 ) - GUILayout.Box( "No results found...", Utilities.GL_EXPAND_WIDTH ); - else - { - GUILayout.BeginHorizontal(); - - // Select all the references after filtering them (select only the GameObject's) - if( GUILayout.Button( "Select All\n(GameObject-wise)", Utilities.GL_HEIGHT_35 ) ) - { - HashSet uniqueGameObjects = new HashSet(); - for( int i = 0; i < searchResult.Count; i++ ) - searchResult[i].AddGameObjectsTo( uniqueGameObjects ); - - if( uniqueGameObjects.Count > 0 ) + foreach( Object target in searchParameters.searchInAssetsSubset ) { - GameObject[] objects = new GameObject[uniqueGameObjects.Count]; - uniqueGameObjects.CopyTo( objects ); - Selection.objects = objects; + if( target == null || target.Equals( null ) ) + continue; + + if( target.IsFolder() ) + folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( target ) ); + else + folderContentsSet.Add( AssetDatabase.GetAssetPath( target ) ); + } + + assetPaths = folderContentsSet; + } + + foreach( string path in assetPaths ) + { + // If asset resides inside the Assets directory and is not a scene asset + if( path.StartsWith( "Assets/" ) && !path.EndsWith( ".unity" ) ) + { + if( !AssetHasAnyReferenceTo( path, assetsToSearchPathsSet ) ) + continue; + + Object[] assets = AssetDatabase.LoadAllAssetsAtPath( path ); + if( assets == null || assets.Length == 0 ) + continue; + + for( int i = 0; i < assets.Length; i++ ) + BeginSearchObject( assets[i] ); } } - // Select all the references without filtering them - if( GUILayout.Button( "Select All\n(Object-wise)", Utilities.GL_HEIGHT_35 ) ) - { - HashSet uniqueObjects = new HashSet(); - for( int i = 0; i < searchResult.Count; i++ ) - searchResult[i].AddObjectsTo( uniqueObjects ); - - if( uniqueObjects.Count > 0 ) - { - Object[] objects = new Object[uniqueObjects.Count]; - uniqueObjects.CopyTo( objects ); - Selection.objects = objects; - } - } - - GUILayout.EndHorizontal(); - - GUILayout.Space( 10 ); - - showTooltips = EditorGUILayout.ToggleLeft( "Show tooltips", showTooltips ); - - GUILayout.Space( 10 ); - - GUILayout.Label( "Path drawing mode:" ); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references (can be slow with too many references)", pathDrawingMode == PathDrawingMode.Full ) ) - pathDrawingMode = PathDrawingMode.Full; - - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant unique parts of the complete paths that start with a UnityEngine.Object", pathDrawingMode == PathDrawingMode.ShortRelevantParts ) ) - pathDrawingMode = PathDrawingMode.ShortRelevantParts; - - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths that are unique", pathDrawingMode == PathDrawingMode.Shortest ) ) - pathDrawingMode = PathDrawingMode.Shortest; - - GUILayout.EndHorizontal(); - - // Tooltip gets its value in ReferenceHolder.DrawOnGUI function - tooltip = null; - for( int i = 0; i < searchResult.Count; i++ ) - searchResult[i].DrawOnGUI( pathDrawingMode ); - - if( tooltip != null ) - { - // Show tooltip at mouse position - Vector2 mousePos = Event.current.mousePosition; - Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( tooltip ) ); - - GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), tooltip, Utilities.TooltipGUIStyle ); - } + // If a reference is found in the Project view, save the results + if( currentSearchResultGroup.NumberOfReferences > 0 ) + searchResult.Add( currentSearchResultGroup ); } - } - GUILayout.Space( 10 ); + // Search non-serializable variables for references only if we are currently searching a scene and the editor is in play mode + if( EditorApplication.isPlaying ) + searchSerializableVariablesOnly = false; - GUILayout.EndVertical(); - - EditorGUILayout.EndScrollView(); - } - - // Exposes objectsToSearch as an array field on GUI - private bool ExposeSearchedObjects() - { - bool hasChanged = false; - bool guiEnabled = GUI.enabled; - - Event ev = Event.current; - - GUILayout.BeginHorizontal(); - - GUILayout.Label( "Asset(s):" ); - - if( guiEnabled ) - { - // Handle drag & drop references to array - // Credit: https://answers.unity.com/answers/657877/view.html - if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && - GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) ) + foreach( string scenePath in scenesToSearch ) { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if( ev.type == EventType.DragPerform ) - { - DragAndDrop.AcceptDrag(); - - Object[] draggedObjects = DragAndDrop.objectReferences; - if( draggedObjects.Length > 0 ) - { - for( int i = 0; i < draggedObjects.Length; i++ ) - { - if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) ) - { - hasChanged = true; - objectsToSearch.Add( new ObjectToSearch( draggedObjects[i] ) ); - } - } - } - } - - ev.Use(); + // Search scene for references + if( !string.IsNullOrEmpty( scenePath ) ) + SearchScene( scenePath, searchResult, initialSceneSetup ); } - if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) - objectsToSearch.Insert( 0, new ObjectToSearch( null ) ); - } - - GUILayout.EndHorizontal(); - - for( int i = 0; i < objectsToSearch.Count; i++ ) - { - ObjectToSearch objToSearch = objectsToSearch[i]; - - GUI.changed = false; - GUILayout.BeginHorizontal(); - - Object prevAssetToSearch = objToSearch.obj; - objToSearch.obj = EditorGUILayout.ObjectField( "", objToSearch.obj, typeof( Object ), true ); - - if( GUI.changed && prevAssetToSearch != objToSearch.obj ) + // Search through all the GameObjects under the DontDestroyOnLoad scene (if exists) + if( EditorApplication.isPlaying ) { - hasChanged = true; - objToSearch.RefreshSubAssets(); + currentSearchResultGroup = new SearchResultGroup( "DontDestroyOnLoad", false ); + + GameObject[] rootGameObjects = GetDontDestroyOnLoadObjects(); + for( int i = 0; i < rootGameObjects.Length; i++ ) + SearchGameObjectRecursively( rootGameObjects[i] ); + + if( currentSearchResultGroup.NumberOfReferences > 0 ) + searchResult.Add( currentSearchResultGroup ); } - if( guiEnabled ) - { - if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) - objectsToSearch.Insert( i + 1, new ObjectToSearch( null ) ); + for( int i = 0; i < searchResult.Count; i++ ) + searchResult[i].InitializeNodes(); - if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) ) - { - if( objToSearch != null && !objToSearch.Equals( null ) ) - hasChanged = true; + // Log some c00l stuff to console + Debug.Log( "Searched " + searchedObjectsCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" ); - objectsToSearch.RemoveAt( i-- ); - } - } - - GUILayout.EndHorizontal(); - - List subAssetsToSearch = objToSearch.subAssets; - if( subAssetsToSearch.Count > 0 ) - { - GUILayout.BeginHorizontal(); - - // 0-> all toggles off, 1-> mixed, 2-> all toggles on - bool toggleAllSubAssets = subAssetsToSearch[0].shouldSearch; - bool mixedToggle = false; - for( int j = 1; j < subAssetsToSearch.Count; j++ ) - { - if( subAssetsToSearch[j].shouldSearch != toggleAllSubAssets ) - { - mixedToggle = true; - break; - } - } - - if( mixedToggle ) - EditorGUI.showMixedValue = true; - - GUI.changed = false; - toggleAllSubAssets = EditorGUILayout.Toggle( toggleAllSubAssets, Utilities.GL_WIDTH_25 ); - if( GUI.changed ) - { - for( int j = 0; j < subAssetsToSearch.Count; j++ ) - subAssetsToSearch[j].shouldSearch = toggleAllSubAssets; - } - - EditorGUI.showMixedValue = false; - - objToSearch.showSubAssetsFoldout = EditorGUILayout.Foldout( objToSearch.showSubAssetsFoldout, "Include sub-assets in search:", true ); - - GUILayout.EndHorizontal(); - - if( objToSearch.showSubAssetsFoldout ) - { - for( int j = 0; j < subAssetsToSearch.Count; j++ ) - { - GUILayout.BeginHorizontal(); - - subAssetsToSearch[j].shouldSearch = EditorGUILayout.Toggle( subAssetsToSearch[j].shouldSearch, Utilities.GL_WIDTH_25 ); - - GUI.enabled = false; - EditorGUILayout.ObjectField( string.Empty, subAssetsToSearch[j].subAsset, typeof( Object ), true ); - GUI.enabled = guiEnabled; - - GUILayout.EndHorizontal(); - } - } - } + currentSearchResultGroup = null; + return new SearchResult( searchResult, initialSceneSetup ); } - - return hasChanged; - } - - private bool AreSearchedObjectsEmpty() - { - for( int i = 0; i < objectsToSearch.Count; i++ ) + catch( Exception e ) { - if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) ) - return false; + Debug.LogException( e ); + return new SearchResult( null, initialSceneSetup ); } - - return true; - } - - // Exposes searchInAssets as an array field on GUI - private void ExposeAssetsToSearch() - { - Event ev = Event.current; - - GUILayout.BeginHorizontal(); - - GUILayout.Label( "Search in following asset(s) only:" ); - - // Handle drag & drop references to array - // Credit: https://answers.unity.com/answers/657877/view.html - if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && - GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) ) - { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if( ev.type == EventType.DragPerform ) - { - DragAndDrop.AcceptDrag(); - - Object[] draggedObjects = DragAndDrop.objectReferences; - if( draggedObjects.Length > 0 ) - { - for( int i = 0; i < draggedObjects.Length; i++ ) - { - if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) ) - searchInAssets.Add( draggedObjects[i] ); - } - } - } - - ev.Use(); - } - - if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) - searchInAssets.Insert( 0, null ); - - GUILayout.EndHorizontal(); - - for( int i = 0; i < searchInAssets.Count; i++ ) - { - GUILayout.BeginHorizontal(); - - searchInAssets[i] = EditorGUILayout.ObjectField( "", searchInAssets[i], typeof( Object ), true ); - - if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) - searchInAssets.Insert( i + 1, null ); - - if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) ) - searchInAssets.RemoveAt( i-- ); - - GUILayout.EndHorizontal(); - } - } - - private bool AreAssetsToSearchEmpty() - { - for( int i = 0; i < searchInAssets.Count; i++ ) - { - if( searchInAssets[i] != null && !searchInAssets[i].Equals( null ) ) - return false; - } - - return true; - } - - // Search for references! - private void ExecuteQuery() - { - searchCount = 0; - searchStartTime = EditorApplication.timeSinceStartup; - - // Initialize commonly used variables - if( searchResult == null ) - searchResult = new List( 16 ); - else - searchResult.Clear(); - - if( typeToVariables == null ) - typeToVariables = new Dictionary( 4096 ); - else if( searchDepthLimit != prevSearchDepthLimit || prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers ) - typeToVariables.Clear(); - - if( searchedObjects == null ) - searchedObjects = new Dictionary( 32768 ); - else - searchedObjects.Clear(); - - if( callStack == null ) - callStack = new Stack( 64 ); - else - callStack.Clear(); - - if( objectsToSearchSet == null ) - objectsToSearchSet = new HashSet(); - else - objectsToSearchSet.Clear(); - - if( sceneObjectsToSearchSet == null ) - sceneObjectsToSearchSet = new HashSet(); - else - sceneObjectsToSearchSet.Clear(); - - if( sceneObjectsToSearchScenesSet == null ) - sceneObjectsToSearchScenesSet = new HashSet(); - else - sceneObjectsToSearchScenesSet.Clear(); - - if( assetsToSearchSet == null ) - assetsToSearchSet = new HashSet(); - else - assetsToSearchSet.Clear(); - - if( assetsToSearchPathsSet == null ) - assetsToSearchPathsSet = new HashSet(); - else - assetsToSearchPathsSet.Clear(); - - if( assetDependencyCache == null ) - { - LoadCache(); - searchStartTime = EditorApplication.timeSinceStartup; - } - else - { - foreach( var cacheEntry in assetDependencyCache.Values ) - cacheEntry.verified = false; - } - - prevSearchDepthLimit = searchDepthLimit; - prevFieldModifiers = fieldModifiers; - prevPropertyModifiers = propertyModifiers; - - searchPrefabConnections = false; - searchMonoBehavioursForScript = false; - searchRenderers = false; - searchMaterialsForShader = false; - searchMaterialsForTexture = false; - - // Store the searched asset(s) and their sub-assets (if any) in HashSets - for( int i = 0; i < objectsToSearch.Count; i++ ) - { - AddSearchedObjectToFilteredSets( objectsToSearch[i].obj ); - - List subAssets = objectsToSearch[i].subAssets; - for( int j = 0; j < subAssets.Count; j++ ) - { - if( subAssets[j].shouldSearch ) - AddSearchedObjectToFilteredSets( subAssets[j].subAsset ); - } - } - - foreach( Object obj in objectsToSearchSet ) - { - // Initialize the nodes of searched asset(s) - searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) ); - - if( obj is Texture ) - { - searchRenderers = true; - searchMaterialsForTexture = true; - } - else if( obj is Material ) - { - searchRenderers = true; - } - else if( obj is MonoScript ) - { - searchMonoBehavioursForScript = true; - } - else if( obj is Shader ) - { - searchRenderers = true; - searchMaterialsForShader = true; - } - else if( obj is GameObject ) - { - searchPrefabConnections = true; - } - } - - // Find the scenes to search for references - HashSet scenesToSearch = new HashSet(); - if( searchInAllScenes ) - { - // Get all scenes from the Assets folder - string[] sceneGuids = AssetDatabase.FindAssets( "t:SceneAsset" ); - for( int i = 0; i < sceneGuids.Length; i++ ) - scenesToSearch.Add( AssetDatabase.GUIDToAssetPath( sceneGuids[i] ) ); - } - else - { - if( searchInOpenScenes ) - { - // Get all open (and loaded) scenes - for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) - { - Scene scene = EditorSceneManager.GetSceneAt( i ); - if( scene.IsValid() ) - scenesToSearch.Add( scene.path ); - } - } - - if( searchInScenesInBuild ) - { - // Get all scenes in build settings - EditorBuildSettingsScene[] scenesTemp = EditorBuildSettings.scenes; - for( int i = 0; i < scenesTemp.Length; i++ ) - { - if( !searchInScenesInBuildTickedOnly || scenesTemp[i].enabled ) - scenesToSearch.Add( scenesTemp[i].path ); - } - } - } - - // By default, search only serializable variables for references - searchSerializableVariablesOnly = true; - - // Don't search assets if searched object(s) are all scene objects as assets can't hold references to scene objects - if( searchInAssetsFolder && assetsToSearchSet.Count > 0 ) - { - currentReferenceHolder = new ReferenceHolder( "Project View (Assets)", false ); - - // Get the paths of all assets that are to be searched - IEnumerable assetPaths; - if( AreAssetsToSearchEmpty() ) - assetPaths = AssetDatabase.GetAllAssetPaths(); - else - { - HashSet temp = new HashSet(); - for( int i = 0; i < searchInAssets.Count; i++ ) - { - Object target = searchInAssets[i]; - string targetPath = AssetDatabase.GetAssetPath( target ); - if( target is DefaultAsset && AssetDatabase.IsValidFolder( targetPath ) ) - { - string[] folderContents = AssetDatabase.FindAssets( "", new string[] { targetPath } ); - for( int j = 0; j < folderContents.Length; j++ ) - { - string filePath = AssetDatabase.GUIDToAssetPath( folderContents[j] ); - if( !string.IsNullOrEmpty( filePath ) && !AssetDatabase.IsValidFolder( filePath ) ) - temp.Add( filePath ); - } - } - else - temp.Add( targetPath ); - } - - assetPaths = temp; - } - - foreach( string path in assetPaths ) - { - // If asset resides inside the Assets directory and is not a scene asset - if( path.StartsWith( "Assets/" ) && !path.EndsWith( ".unity" ) ) - { - if( !AssetHasAnyReferenceTo( path, assetsToSearchPathsSet ) ) - continue; - - Object[] assets = AssetDatabase.LoadAllAssetsAtPath( path ); - if( assets == null || assets.Length == 0 ) - continue; - - for( int i = 0; i < assets.Length; i++ ) - BeginSearchObject( assets[i] ); - } - } - - // If a reference is found in the Project view, save the results - if( currentReferenceHolder.NumberOfReferences > 0 ) - searchResult.Add( currentReferenceHolder ); - } - - // Search non-serializable variables for references only if we are currently searching a scene and the editor is in play mode - if( EditorApplication.isPlaying ) - searchSerializableVariablesOnly = false; - - foreach( string scenePath in scenesToSearch ) - { - // Search scene for references - if( !string.IsNullOrEmpty( scenePath ) ) - SearchScene( scenePath ); - } - - // Search through all the GameObjects under the DontDestroyOnLoad scene (if exists) - if( EditorApplication.isPlaying ) - { - currentReferenceHolder = new ReferenceHolder( "DontDestroyOnLoad", false ); - - GameObject[] rootGameObjects = GetDontDestroyOnLoadObjects(); - for( int i = 0; i < rootGameObjects.Length; i++ ) - SearchGameObjectRecursively( rootGameObjects[i] ); - - if( currentReferenceHolder.NumberOfReferences > 0 ) - searchResult.Add( currentReferenceHolder ); - } - - for( int i = 0; i < searchResult.Count; i++ ) - searchResult[i].InitializeNodes(); - - // Log some c00l stuff to console - Debug.Log( "Searched " + searchCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" ); - - // Search is complete! - currentPhase = Phase.Complete; } // Checks if object is asset or scene object and adds it to the corresponding HashSet(s) @@ -967,7 +436,7 @@ namespace AssetUsageDetectorNamespace } // Search a scene for references - private void SearchScene( string scenePath ) + private void SearchScene( string scenePath, List searchResult, SceneSetup[] initialSceneSetup ) { Scene scene = EditorSceneManager.GetSceneByPath( scenePath ); @@ -982,7 +451,7 @@ namespace AssetUsageDetectorNamespace if( !EditorApplication.isPlaying ) scene = EditorSceneManager.OpenScene( scenePath, OpenSceneMode.Additive ); - currentReferenceHolder = new ReferenceHolder( scenePath, true ); + currentSearchResultGroup = new SearchResultGroup( scenePath, true ); // Search through all the GameObjects in the scene GameObject[] rootGameObjects = scene.GetRootGameObjects(); @@ -990,7 +459,7 @@ namespace AssetUsageDetectorNamespace SearchGameObjectRecursively( rootGameObjects[i] ); // If no references are found in the scene and if the scene is not part of the initial scene setup, close it - if( currentReferenceHolder.NumberOfReferences == 0 ) + if( currentSearchResultGroup.NumberOfReferences == 0 ) { if( !EditorApplication.isPlaying ) { @@ -1014,7 +483,7 @@ namespace AssetUsageDetectorNamespace else { // Some references are found in this scene, save the results - searchResult.Add( currentReferenceHolder ); + searchResult.Add( currentSearchResultGroup ); } } @@ -1055,7 +524,7 @@ namespace AssetUsageDetectorNamespace } if( referenceNode.NumberOfOutgoingLinks > 0 ) - currentReferenceHolder.AddReference( referenceNode ); + currentSearchResultGroup.AddReference( referenceNode ); else PoolReferenceNode( referenceNode ); } @@ -1065,7 +534,7 @@ namespace AssetUsageDetectorNamespace ReferenceNode searchResult = SearchObject( obj ); if( searchResult != null ) - currentReferenceHolder.AddReference( searchResult ); + currentSearchResultGroup.AddReference( searchResult ); } // Search an object for references @@ -1090,7 +559,7 @@ namespace AssetUsageDetectorNamespace return cachedResult; } - searchCount++; + searchedObjectsCount++; ReferenceNode result; Object unityObject = obj as Object; @@ -1534,55 +1003,7 @@ namespace AssetUsageDetectorNamespace } } - // Check if all open scenes are saved (not dirty) - private bool AreScenesSaved() - { - for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) - { - Scene scene = EditorSceneManager.GetSceneAt( i ); - if( scene.isDirty || string.IsNullOrEmpty( scene.path ) ) - return false; - } - - return true; - } - - // Close the scenes that were not part of the initial scene setup - private bool RestoreInitialSceneSetup() - { - if( EditorApplication.isPlaying || initialSceneSetup == null ) - return true; - - if( !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() ) - return false; - - SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup(); - for( int i = 0; i < sceneFinalSetup.Length; i++ ) - { - bool sceneIsOneOfInitials = false; - for( int j = 0; j < initialSceneSetup.Length; j++ ) - { - if( sceneFinalSetup[i].path == initialSceneSetup[j].path ) - { - sceneIsOneOfInitials = true; - break; - } - } - - if( !sceneIsOneOfInitials ) - EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( sceneFinalSetup[i].path ), true ); - } - - for( int i = 0; i < initialSceneSetup.Length; i++ ) - { - if( !initialSceneSetup[i].isLoaded ) - EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( initialSceneSetup[i].path ), false ); - } - - return true; - } - - private void SaveCache() + public void SaveCache() { if( assetDependencyCache == null ) return; diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs new file mode 100644 index 0000000..cee3434 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs @@ -0,0 +1,584 @@ +// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com) + +using UnityEngine; +using UnityEditor; +using UnityEngine.SceneManagement; +using UnityEditor.SceneManagement; +using System.Collections.Generic; +using System.Reflection; +using Object = UnityEngine.Object; + +namespace AssetUsageDetectorNamespace +{ + public enum Phase { Setup, Processing, Complete }; + public enum PathDrawingMode { Full, ShortRelevantParts, Shortest }; + + public class AssetUsageDetectorWindow : EditorWindow + { + private const float PLAY_MODE_REFRESH_INTERVAL = 1f; // Interval to refresh the editor window in play mode + + private AssetUsageDetector core = new AssetUsageDetector(); + private SearchResult searchResult; // Overall search results + + private List objectsToSearch = new List() { new ObjectToSearch( null ) }; + + private Phase currentPhase = Phase.Setup; + + private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view + private bool searchInScenesInBuild = true; // Scenes in build + private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not) + private bool searchInAllScenes = true; // All scenes (including scenes that are not in build) + private bool searchInAssetsFolder = true; // Assets in Project view + + private List searchInAssetsSubset = new List() { null }; // If not empty, only these assets are searched for references + + private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects + + private bool restoreInitialSceneSetup = true; // Close the additively loaded scenes that were not part of the initial scene setup + + private string errorMessage = string.Empty; + private bool noAssetDatabaseChanges = false; + + // Fetch public, protected and private non-static fields and properties from objects by default + private BindingFlags fieldModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic; + private BindingFlags propertyModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic; + + private SearchResultDrawParameters searchResultDrawParameters = new SearchResultDrawParameters( PathDrawingMode.ShortRelevantParts, false ); + + private double nextPlayModeRefreshTime = 0f; + + private Vector2 scrollPosition = Vector2.zero; + + // Add "Asset Usage Detector" menu item to the Window menu + [MenuItem( "Window/Asset Usage Detector" )] + private static void Init() + { + AssetUsageDetectorWindow window = GetWindow(); + window.titleContent = new GUIContent( "Asset Usage Detector" ); + window.minSize = new Vector2( 325f, 220f ); + window.Show(); + } + + private void OnDisable() + { + if( core != null ) + core.SaveCache(); + } + + private void OnDestroy() + { + if( searchResult != null && currentPhase == Phase.Complete && !EditorApplication.isPlaying && searchResult.InitialSceneSetupConfigured ) + { + if( EditorUtility.DisplayDialog( "Scenes", "Restore initial scene setup?", "Yes", "Leave it as is" ) ) + searchResult.RestoreInitialSceneSetup(); + } + } + + private void Update() + { + // Refresh the window at a regular interval in play mode to update the tooltip + if( EditorApplication.isPlaying && currentPhase == Phase.Complete && searchResultDrawParameters.showTooltips && EditorApplication.timeSinceStartup >= nextPlayModeRefreshTime ) + { + nextPlayModeRefreshTime = EditorApplication.timeSinceStartup + PLAY_MODE_REFRESH_INTERVAL; ; + Repaint(); + } + } + + private void OnGUI() + { + // Make the window scrollable + scrollPosition = EditorGUILayout.BeginScrollView( scrollPosition, Utilities.GL_EXPAND_WIDTH, Utilities.GL_EXPAND_HEIGHT ); + + GUILayout.BeginVertical(); + + GUILayout.Space( 10 ); + + // Show the error message, if it is not empty + if( errorMessage.Length > 0 ) + EditorGUILayout.HelpBox( errorMessage, MessageType.Error ); + + GUILayout.Space( 10 ); + + if( currentPhase == Phase.Processing ) + { + // If we are stuck at this phase, then we have encountered an exception + GUILayout.Label( ". . . Something went wrong, check console . . ." ); + + restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup (Recommended)", restoreInitialSceneSetup ); + + if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) ) + ReturnToSetupPhase( restoreInitialSceneSetup ); + } + else if( currentPhase == Phase.Setup ) + { + if( ExposeSearchedObjects() ) + errorMessage = string.Empty; + + GUILayout.Space( 10 ); + + GUILayout.Box( "SEARCH IN", Utilities.GL_EXPAND_WIDTH ); + + searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project view (Assets folder)", searchInAssetsFolder ); + + if( searchInAssetsFolder ) + { + GUILayout.BeginHorizontal(); + GUILayout.Space( 35 ); + GUILayout.BeginVertical(); + + ExposeAssetsToSearch(); + + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + + GUILayout.Space( 10 ); + + if( EditorApplication.isPlaying ) + { + searchInAllScenes = false; + searchInScenesInBuild = false; + } + else if( searchInAllScenes ) + GUI.enabled = false; + + searchInOpenScenes = EditorGUILayout.ToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes ); + + if( EditorApplication.isPlaying ) + GUI.enabled = false; + + searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", searchInScenesInBuild ); + + if( searchInScenesInBuild ) + { + GUILayout.BeginHorizontal(); + GUILayout.Space( 35 ); + + searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); + searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); + + GUILayout.EndHorizontal(); + } + + if( !EditorApplication.isPlaying ) + GUI.enabled = true; + + searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes ); + + GUI.enabled = true; + + GUILayout.Space( 10 ); + + GUILayout.Box( "SEARCH SETTINGS", Utilities.GL_EXPAND_WIDTH ); + + GUILayout.BeginHorizontal(); + + GUILayout.Label( new GUIContent( "> Search depth: " + searchDepthLimit, "Depth limit for recursively searching variables of objects" ), Utilities.GL_WIDTH_250 ); + + searchDepthLimit = (int) GUILayout.HorizontalSlider( searchDepthLimit, 0, 4 ); + + GUILayout.EndHorizontal(); + + GUILayout.Label( "> Search variables:" ); + + GUILayout.BeginHorizontal(); + + GUILayout.Space( 35 ); + + if( EditorGUILayout.ToggleLeft( "Public", ( fieldModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) + fieldModifiers |= BindingFlags.Public; + else + fieldModifiers &= ~BindingFlags.Public; + + if( EditorGUILayout.ToggleLeft( "Non-public", ( fieldModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) + fieldModifiers |= BindingFlags.NonPublic; + else + fieldModifiers &= ~BindingFlags.NonPublic; + + GUILayout.EndHorizontal(); + + GUILayout.Label( "> Search properties (can be slow):" ); + + GUILayout.BeginHorizontal(); + + GUILayout.Space( 35 ); + + if( EditorGUILayout.ToggleLeft( "Public", ( propertyModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) + propertyModifiers |= BindingFlags.Public; + else + propertyModifiers &= ~BindingFlags.Public; + + if( EditorGUILayout.ToggleLeft( "Non-public", ( propertyModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) + propertyModifiers |= BindingFlags.NonPublic; + else + propertyModifiers &= ~BindingFlags.NonPublic; + + GUILayout.EndHorizontal(); + + GUILayout.Space( 10 ); + + // Don't let the user press the GO button without any valid search location + if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder ) + GUI.enabled = false; + + noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges ); + + if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) ) + { + if( objectsToSearch.IsEmpty() ) + errorMessage = "ADD AN ASSET TO THE LIST FIRST!"; + else if( !EditorApplication.isPlaying && !AreScenesSaved() ) + { + // Don't start the search if at least one scene is currently dirty (not saved) + errorMessage = "SAVE OPEN SCENES FIRST!"; + } + else + { + errorMessage = string.Empty; + currentPhase = Phase.Processing; + + SceneSearchMode sceneSearchMode = SceneSearchMode.None; + if( searchInAllScenes ) + sceneSearchMode = SceneSearchMode.AllScenes; + else + { + if( searchInOpenScenes ) + sceneSearchMode = SceneSearchMode.OpenScenes; + + if( searchInScenesInBuild ) + { + if( searchInScenesInBuildTickedOnly ) + sceneSearchMode |= SceneSearchMode.ScenesInBuildSettingsTickedOnly; + else + sceneSearchMode |= SceneSearchMode.ScenesInBuildSettingsAll; + } + } + + // Start searching + searchResult = core.Run( new AssetUsageDetector.Parameters() + { + objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ) : null, + searchInScenes = sceneSearchMode, + searchInAssetsFolder = searchInAssetsFolder, + searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset : null, + fieldModifiers = fieldModifiers, + propertyModifiers = propertyModifiers, + searchDepthLimit = searchDepthLimit, + noAssetDatabaseChanges = noAssetDatabaseChanges + } ); + + currentPhase = Phase.Complete; + } + } + } + else if( currentPhase == Phase.Complete ) + { + // Draw the results of the search + GUI.enabled = false; + + ExposeSearchedObjects(); + + GUILayout.Space( 10 ); + GUI.enabled = true; + + restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup after search is reset (Recommended)", restoreInitialSceneSetup ); + + if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) ) + ReturnToSetupPhase( restoreInitialSceneSetup ); + + if( searchResult == null ) + { + EditorGUILayout.HelpBox( "ERROR: searchResult is null", MessageType.Error ); + return; + } + + Color c = GUI.color; + GUI.color = Color.green; + GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.GL_EXPAND_WIDTH ); + GUI.color = c; + + GUILayout.Space( 10 ); + + if( searchResult.Count == 0 ) + GUILayout.Box( "No results found...", Utilities.GL_EXPAND_WIDTH ); + else + { + GUILayout.BeginHorizontal(); + + // Select all the references after filtering them (select only the GameObject's) + if( GUILayout.Button( "Select All\n(GameObject-wise)", Utilities.GL_HEIGHT_35 ) ) + { + GameObject[] objects = searchResult.SelectAllAsGameObjects(); + if( objects != null && objects.Length > 0 ) + Selection.objects = objects; + } + + // Select all the references without filtering them + if( GUILayout.Button( "Select All\n(Object-wise)", Utilities.GL_HEIGHT_35 ) ) + { + Object[] objects = searchResult.SelectAllAsObjects(); + if( objects != null && objects.Length > 0 ) + Selection.objects = objects; + } + + GUILayout.EndHorizontal(); + + GUILayout.Space( 10 ); + + searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( "Show tooltips", searchResultDrawParameters.showTooltips ); + + GUILayout.Space( 10 ); + + GUILayout.Label( "Path drawing mode:" ); + + GUILayout.BeginHorizontal(); + + 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 ) ) + searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full; + + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + + 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 ) ) + searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts; + + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + + GUILayout.Space( 35 ); + + if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths that are unique", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) ) + searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest; + + GUILayout.EndHorizontal(); + + searchResult.DrawOnGUI( searchResultDrawParameters ); + } + } + + GUILayout.Space( 10 ); + + GUILayout.EndVertical(); + + EditorGUILayout.EndScrollView(); + } + + // Exposes objectsToSearch as an array field on GUI + private bool ExposeSearchedObjects() + { + bool hasChanged = false; + bool guiEnabled = GUI.enabled; + + Event ev = Event.current; + + GUILayout.BeginHorizontal(); + + GUILayout.Label( "Asset(s):" ); + + if( guiEnabled ) + { + // Handle drag & drop references to array + // Credit: https://answers.unity.com/answers/657877/view.html + if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && + GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) ) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if( ev.type == EventType.DragPerform ) + { + DragAndDrop.AcceptDrag(); + + Object[] draggedObjects = DragAndDrop.objectReferences; + if( draggedObjects.Length > 0 ) + { + for( int i = 0; i < draggedObjects.Length; i++ ) + { + if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) ) + { + hasChanged = true; + objectsToSearch.Add( new ObjectToSearch( draggedObjects[i] ) ); + } + } + } + } + + ev.Use(); + } + + if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) + objectsToSearch.Insert( 0, new ObjectToSearch( null ) ); + } + + GUILayout.EndHorizontal(); + + for( int i = 0; i < objectsToSearch.Count; i++ ) + { + ObjectToSearch objToSearch = objectsToSearch[i]; + + GUI.changed = false; + GUILayout.BeginHorizontal(); + + Object prevAssetToSearch = objToSearch.obj; + objToSearch.obj = EditorGUILayout.ObjectField( "", objToSearch.obj, typeof( Object ), true ); + + if( GUI.changed && prevAssetToSearch != objToSearch.obj ) + { + hasChanged = true; + objToSearch.RefreshSubAssets(); + } + + if( guiEnabled ) + { + if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) + objectsToSearch.Insert( i + 1, new ObjectToSearch( null ) ); + + if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) ) + { + if( objToSearch != null && !objToSearch.Equals( null ) ) + hasChanged = true; + + objectsToSearch.RemoveAt( i-- ); + } + } + + GUILayout.EndHorizontal(); + + List subAssetsToSearch = objToSearch.subAssets; + if( subAssetsToSearch.Count > 0 ) + { + GUILayout.BeginHorizontal(); + + // 0-> all toggles off, 1-> mixed, 2-> all toggles on + bool toggleAllSubAssets = subAssetsToSearch[0].shouldSearch; + bool mixedToggle = false; + for( int j = 1; j < subAssetsToSearch.Count; j++ ) + { + if( subAssetsToSearch[j].shouldSearch != toggleAllSubAssets ) + { + mixedToggle = true; + break; + } + } + + if( mixedToggle ) + EditorGUI.showMixedValue = true; + + GUI.changed = false; + toggleAllSubAssets = EditorGUILayout.Toggle( toggleAllSubAssets, Utilities.GL_WIDTH_25 ); + if( GUI.changed ) + { + for( int j = 0; j < subAssetsToSearch.Count; j++ ) + subAssetsToSearch[j].shouldSearch = toggleAllSubAssets; + } + + EditorGUI.showMixedValue = false; + + objToSearch.showSubAssetsFoldout = EditorGUILayout.Foldout( objToSearch.showSubAssetsFoldout, "Include sub-assets in search:", true ); + + GUILayout.EndHorizontal(); + + if( objToSearch.showSubAssetsFoldout ) + { + for( int j = 0; j < subAssetsToSearch.Count; j++ ) + { + GUILayout.BeginHorizontal(); + + subAssetsToSearch[j].shouldSearch = EditorGUILayout.Toggle( subAssetsToSearch[j].shouldSearch, Utilities.GL_WIDTH_25 ); + + GUI.enabled = false; + EditorGUILayout.ObjectField( string.Empty, subAssetsToSearch[j].subAsset, typeof( Object ), true ); + GUI.enabled = guiEnabled; + + GUILayout.EndHorizontal(); + } + } + } + } + + return hasChanged; + } + + // Exposes searchInAssetsSubset as an array field on GUI + private void ExposeAssetsToSearch() + { + Event ev = Event.current; + + GUILayout.BeginHorizontal(); + + GUILayout.Label( "Search in following asset(s) only:" ); + + // Handle drag & drop references to array + // Credit: https://answers.unity.com/answers/657877/view.html + if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && + GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) ) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if( ev.type == EventType.DragPerform ) + { + DragAndDrop.AcceptDrag(); + + Object[] draggedObjects = DragAndDrop.objectReferences; + if( draggedObjects.Length > 0 ) + { + for( int i = 0; i < draggedObjects.Length; i++ ) + { + if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) ) + searchInAssetsSubset.Add( draggedObjects[i] ); + } + } + } + + ev.Use(); + } + + if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) + searchInAssetsSubset.Insert( 0, null ); + + GUILayout.EndHorizontal(); + + for( int i = 0; i < searchInAssetsSubset.Count; i++ ) + { + GUILayout.BeginHorizontal(); + + searchInAssetsSubset[i] = EditorGUILayout.ObjectField( "", searchInAssetsSubset[i], typeof( Object ), false ); + + if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) + searchInAssetsSubset.Insert( i + 1, null ); + + if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) ) + searchInAssetsSubset.RemoveAt( i-- ); + + GUILayout.EndHorizontal(); + } + } + + // Check if all open scenes are saved (not dirty) + private bool AreScenesSaved() + { + for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ ) + { + Scene scene = EditorSceneManager.GetSceneAt( i ); + if( scene.isDirty || string.IsNullOrEmpty( scene.path ) ) + return false; + } + + return true; + } + + private void ReturnToSetupPhase( bool restoreInitialSceneSetup ) + { + if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() ) + return; + + searchResult = null; + + errorMessage = string.Empty; + currentPhase = Phase.Setup; + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs.meta b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs.meta new file mode 100644 index 0000000..95c1c9f --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 271a22c69c3d96c4dbdd04cca415a840 +timeCreated: 1520032279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/Enumerators.cs b/Plugins/AssetUsageDetector/Editor/Enumerators.cs new file mode 100644 index 0000000..fb6f911 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/Enumerators.cs @@ -0,0 +1,106 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace AssetUsageDetectorNamespace +{ + public class EmptyEnumerator : IEnumerable, IEnumerator + { + public T Current { get { return default( T ); } } + object IEnumerator.Current { get { return Current; } } + + public void Dispose() { } + public void Reset() { } + + public bool MoveNext() + { + return false; + } + + public IEnumerator GetEnumerator() + { + return this; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this; + } + } + + public class ObjectToSearchEnumerator : IEnumerable, IEnumerator + { + public Object Current + { + get + { + if( subAssetIndex < 0 ) + return source[index].obj; + + return source[index].subAssets[subAssetIndex].subAsset; + } + } + + object IEnumerator.Current { get { return Current; } } + + private List source; + private int index; + private int subAssetIndex; + + public ObjectToSearchEnumerator( List source ) + { + this.source = source; + Reset(); + } + + public void Dispose() + { + source = null; + } + + public bool MoveNext() + { + if( subAssetIndex < -1 ) + { + subAssetIndex = -1; + + if( ++index >= source.Count ) + return false; + + // Skip folder assets in the enumeration, AssetUsageDetector expands encountered folders automatically + // and we don't want that to happen as source[index].subAssets already contains the folder's contents + if( !source[index].obj.IsFolder() ) + return true; + } + + List subAssets = source[index].subAssets; + if( subAssets != null ) + { + while( ++subAssetIndex < subAssets.Count && !subAssets[subAssetIndex].shouldSearch ) + continue; + + if( subAssetIndex < subAssets.Count ) + return true; + } + + subAssetIndex = -2; + return MoveNext(); + } + + public void Reset() + { + index = -1; + subAssetIndex = -2; + } + + public IEnumerator GetEnumerator() + { + return this; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this; + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/Enumerators.cs.meta b/Plugins/AssetUsageDetector/Editor/Enumerators.cs.meta new file mode 100644 index 0000000..19f5248 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/Enumerators.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 894047c47ce45cf40939dae24afcc72b +timeCreated: 1562079461 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs b/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs index ca3e9f3..f4711c9 100644 --- a/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs +++ b/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs @@ -9,8 +9,21 @@ namespace AssetUsageDetectorNamespace [Serializable] public class ObjectToSearch { + [Serializable] + public class SubAsset + { + public Object subAsset; + public bool shouldSearch; + + public SubAsset( Object subAsset, bool shouldSearch ) + { + this.subAsset = subAsset; + this.shouldSearch = shouldSearch; + } + } + public Object obj; - public List subAssets; + public List subAssets; public bool showSubAssetsFoldout; private static MonoScript[] monoScriptsInProject; @@ -25,7 +38,7 @@ namespace AssetUsageDetectorNamespace public void RefreshSubAssets() { if( subAssets == null ) - subAssets = new List(); + subAssets = new List(); else subAssets.Clear(); @@ -35,6 +48,7 @@ namespace AssetUsageDetectorNamespace currentSubAssets.Clear(); AddSubAssets( obj, false ); + currentSubAssets.Clear(); } private void AddSubAssets( Object target, bool includeTarget ) @@ -49,23 +63,17 @@ namespace AssetUsageDetectorNamespace { if( !currentSubAssets.Contains( target ) ) { - subAssets.Add( new SubAssetToSearch( target, true ) ); + subAssets.Add( new SubAsset( target, true ) ); currentSubAssets.Add( target ); } } else { // If asset is a directory, add all of its contents as sub-assets recursively - string targetPath = AssetDatabase.GetAssetPath( target ); - if( target is DefaultAsset && AssetDatabase.IsValidFolder( targetPath ) ) + if( target.IsFolder() ) { - string[] folderContents = AssetDatabase.FindAssets( "", new string[] { targetPath } ); - for( int i = 0; i < folderContents.Length; i++ ) - { - string filePath = AssetDatabase.GUIDToAssetPath( folderContents[i] ); - if( !string.IsNullOrEmpty( filePath ) && !AssetDatabase.IsValidFolder( filePath ) ) - AddSubAssets( AssetDatabase.LoadAssetAtPath( filePath ), true ); - } + foreach( string filePath in Utilities.EnumerateFolderContents( target ) ) + AddSubAssets( AssetDatabase.LoadAssetAtPath( filePath ), true ); return; } @@ -84,7 +92,7 @@ namespace AssetUsageDetectorNamespace if( asset != target ) { - subAssets.Add( new SubAssetToSearch( asset, true ) ); + subAssets.Add( new SubAsset( asset, true ) ); currentSubAssets.Add( asset ); } @@ -114,7 +122,7 @@ namespace AssetUsageDetectorNamespace if( !currentSubAssets.Contains( monoScriptsInProject[j] ) ) { - subAssets.Add( new SubAssetToSearch( monoScriptsInProject[j], true ) ); + subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) ); currentSubAssets.Add( monoScriptsInProject[j] ); } } @@ -122,17 +130,4 @@ namespace AssetUsageDetectorNamespace } } } - - [Serializable] - public class SubAssetToSearch - { - public Object subAsset; - public bool shouldSearch; - - public SubAssetToSearch( Object subAsset, bool shouldSearch ) - { - this.subAsset = subAsset; - this.shouldSearch = shouldSearch; - } - } } \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/ReferenceHolder.cs b/Plugins/AssetUsageDetector/Editor/SearchResult.cs similarity index 60% rename from Plugins/AssetUsageDetector/Editor/ReferenceHolder.cs rename to Plugins/AssetUsageDetector/Editor/SearchResult.cs index 6a52b43..0c0d466 100644 --- a/Plugins/AssetUsageDetector/Editor/ReferenceHolder.cs +++ b/Plugins/AssetUsageDetector/Editor/SearchResult.cs @@ -1,14 +1,212 @@ using System; using System.Collections.Generic; using UnityEditor; +using UnityEditor.SceneManagement; using UnityEngine; using Object = UnityEngine.Object; namespace AssetUsageDetectorNamespace { - // Custom class to hold the results for a single scene or Assets folder [Serializable] - public class ReferenceHolder : ISerializationCallbackReceiver + public class SearchResultDrawParameters + { + public PathDrawingMode pathDrawingMode; + public bool showTooltips; + public string tooltip; + + public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips ) + { + this.pathDrawingMode = pathDrawingMode; + this.showTooltips = showTooltips; + } + } + + // Custom class to hold search results + [Serializable] + public class SearchResult : ISerializationCallbackReceiver + { + // Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html + [Serializable] + public class SerializableResultGroup + { + public string title; + public bool clickable; + + public List initialSerializedNodes; + } + + [Serializable] + public class SerializableNode + { + public int instanceId; + public bool isUnityObject; + public string description; + + public List links; + public List linkDescriptions; + } + + private List result; + private SceneSetup[] initialSceneSetup; + + private List serializedNodes; + private List serializedGroups; + + public int Count { get { return result.Count; } } + public SearchResultGroup this[int index] { get { return result[index]; } } + + public bool SearchCompletedSuccessfully { get { return result != null; } } + public bool InitialSceneSetupConfigured { get { return initialSceneSetup != null; } } + + public SearchResult( List result, SceneSetup[] initialSceneSetup ) + { + if( result == null ) + result = new List( 0 ); + + this.result = result; + this.initialSceneSetup = initialSceneSetup; + } + + public void DrawOnGUI( SearchResultDrawParameters parameters ) + { + parameters.tooltip = null; + + for( int i = 0; i < result.Count; i++ ) + result[i].DrawOnGUI( parameters ); + + if( parameters.tooltip != null ) + { + // Show tooltip at mouse position + Vector2 mousePos = Event.current.mousePosition; + Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( parameters.tooltip ) ); + + GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), parameters.tooltip, Utilities.TooltipGUIStyle ); + } + } + + public Object[] SelectAllAsObjects() + { + HashSet uniqueObjects = new HashSet(); + for( int i = 0; i < result.Count; i++ ) + result[i].AddObjectsTo( uniqueObjects ); + + if( uniqueObjects.Count > 0 ) + { + Object[] objects = new Object[uniqueObjects.Count]; + uniqueObjects.CopyTo( objects ); + + return objects; + } + + return null; + } + + public GameObject[] SelectAllAsGameObjects() + { + HashSet uniqueGameObjects = new HashSet(); + for( int i = 0; i < result.Count; i++ ) + result[i].AddGameObjectsTo( uniqueGameObjects ); + + if( uniqueGameObjects.Count > 0 ) + { + GameObject[] objects = new GameObject[uniqueGameObjects.Count]; + uniqueGameObjects.CopyTo( objects ); + + return objects; + } + + return null; + } + + // Close the scenes that were not part of the initial scene setup + // Returns true if initial scene setup is restored successfully + public bool RestoreInitialSceneSetup() + { + if( initialSceneSetup == null ) + return true; + + if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() ) + return false; + + SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup(); + for( int i = 0; i < sceneFinalSetup.Length; i++ ) + { + bool sceneIsOneOfInitials = false; + for( int j = 0; j < initialSceneSetup.Length; j++ ) + { + if( sceneFinalSetup[i].path == initialSceneSetup[j].path ) + { + sceneIsOneOfInitials = true; + break; + } + } + + if( !sceneIsOneOfInitials ) + EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( sceneFinalSetup[i].path ), true ); + } + + for( int i = 0; i < initialSceneSetup.Length; i++ ) + { + if( !initialSceneSetup[i].isLoaded ) + EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( initialSceneSetup[i].path ), false ); + } + + initialSceneSetup = null; + return true; + } + + // Assembly reloading; serialize nodes in a way that Unity can serialize + void ISerializationCallbackReceiver.OnBeforeSerialize() + { + if( result == null ) + return; + + if( serializedGroups == null ) + serializedGroups = new List( result.Count ); + else + serializedGroups.Clear(); + + if( serializedNodes == null ) + serializedNodes = new List( result.Count * 16 ); + else + serializedNodes.Clear(); + + Dictionary nodeToIndex = new Dictionary( result.Count * 16 ); + for( int i = 0; i < result.Count; i++ ) + serializedGroups.Add( result[i].Serialize( nodeToIndex, serializedNodes ) ); + } + + // Assembly reloaded; deserialize nodes to construct the original graph + void ISerializationCallbackReceiver.OnAfterDeserialize() + { + if( serializedGroups == null || serializedNodes == null ) + return; + + if( result == null ) + result = new List( serializedGroups.Count ); + else + result.Clear(); + + List allNodes = new List( serializedNodes.Count ); + for( int i = 0; i < serializedNodes.Count; i++ ) + allNodes.Add( new ReferenceNode() ); + + for( int i = 0; i < serializedNodes.Count; i++ ) + allNodes[i].Deserialize( serializedNodes[i], allNodes ); + + for( int i = 0; i < serializedGroups.Count; i++ ) + { + result.Add( new SearchResultGroup( serializedGroups[i].title, serializedGroups[i].clickable ) ); + result[i].Deserialize( serializedGroups[i], allNodes ); + } + + serializedNodes.Clear(); + serializedGroups.Clear(); + } + } + + // Custom class to hold the results for a single scene or Assets folder + public class SearchResultGroup { // Custom struct to hold a single path to a reference public struct ReferencePath @@ -23,34 +221,21 @@ namespace AssetUsageDetectorNamespace } } - // Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html - [Serializable] - public class SerializableNode - { - public int instanceId; - public bool isUnityObject; - public string description; + private readonly string title; + private readonly bool clickable; - public List links; - public List linkDescriptions; - } - - private string title; - private bool clickable; - - private List references; + private readonly List references; private List referencePathsShortUnique; private List referencePathsShortest; - private List serializedNodes; - private List initialSerializedNodes; - public int NumberOfReferences { get { return references.Count; } } + public ReferenceNode this[int index] { get { return references[index]; } } - public ReferenceHolder( string title, bool clickable ) + public SearchResultGroup( string title, bool clickable ) { this.title = title; this.clickable = clickable; + references = new List(); referencePathsShortUnique = null; referencePathsShortest = null; @@ -150,7 +335,7 @@ namespace AssetUsageDetectorNamespace } // Draw the results found for this container - public void DrawOnGUI( PathDrawingMode pathDrawingMode ) + public void DrawOnGUI( SearchResultDrawParameters parameters ) { Color c = GUI.color; GUI.color = Color.cyan; @@ -163,13 +348,12 @@ namespace AssetUsageDetectorNamespace GUI.color = Color.yellow; - if( pathDrawingMode == PathDrawingMode.Full ) + if( parameters.pathDrawingMode == PathDrawingMode.Full ) { for( int i = 0; i < references.Count; i++ ) { GUILayout.Space( 5 ); - - references[i].DrawOnGUIRecursively(); + references[i].DrawOnGUIRecursively( parameters, null ); } } else @@ -178,7 +362,7 @@ namespace AssetUsageDetectorNamespace CalculateShortestPathsToReferences(); List pathsToDraw; - if( pathDrawingMode == PathDrawingMode.ShortRelevantParts ) + if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) pathsToDraw = referencePathsShortUnique; else pathsToDraw = referencePathsShortest; @@ -190,13 +374,13 @@ namespace AssetUsageDetectorNamespace GUILayout.BeginHorizontal(); ReferencePath path = pathsToDraw[i]; - path.startNode.DrawOnGUI( null ); + 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( link.description ); + link.targetNode.DrawOnGUI( parameters, link.description ); currentNode = link.targetNode; } @@ -209,53 +393,37 @@ namespace AssetUsageDetectorNamespace GUILayout.Space( 10 ); } - // Assembly reloading; serialize nodes in a way that Unity can serialize - public void OnBeforeSerialize() + // Serialize this result group + public SearchResult.SerializableResultGroup Serialize( Dictionary nodeToIndex, List serializedNodes ) { - if( references == null ) - return; + SearchResult.SerializableResultGroup serializedResultGroup = new SearchResult.SerializableResultGroup() + { + title = title, + clickable = clickable + }; - if( serializedNodes == null ) - serializedNodes = new List( references.Count * 5 ); - else - serializedNodes.Clear(); + if( references != null ) + { + serializedResultGroup.initialSerializedNodes = new List( references.Count ); - if( initialSerializedNodes == null ) - initialSerializedNodes = new List( references.Count ); - else - initialSerializedNodes.Clear(); + for( int i = 0; i < references.Count; i++ ) + serializedResultGroup.initialSerializedNodes.Add( references[i].SerializeRecursively( nodeToIndex, serializedNodes ) ); + } - Dictionary nodeToIndex = new Dictionary( references.Count * 5 ); - for( int i = 0; i < references.Count; i++ ) - initialSerializedNodes.Add( references[i].SerializeRecursively( nodeToIndex, serializedNodes ) ); + return serializedResultGroup; } - // Assembly reloaded; deserialize nodes to construct the original graph - public void OnAfterDeserialize() + // Deserialize this result group from the serialized data + public void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List allNodes ) { - if( initialSerializedNodes == null || serializedNodes == null ) - return; - - if( references == null ) - references = new List( initialSerializedNodes.Count ); - else - references.Clear(); - - List allNodes = new List( serializedNodes.Count ); - for( int i = 0; i < serializedNodes.Count; i++ ) - allNodes.Add( new ReferenceNode() ); - - for( int i = 0; i < serializedNodes.Count; i++ ) - allNodes[i].Deserialize( serializedNodes[i], allNodes ); - - for( int i = 0; i < initialSerializedNodes.Count; i++ ) - references.Add( allNodes[initialSerializedNodes[i]] ); + if( serializedResultGroup.initialSerializedNodes != null ) + { + for( int i = 0; i < serializedResultGroup.initialSerializedNodes.Count; i++ ) + references.Add( allNodes[serializedResultGroup.initialSerializedNodes[i]] ); + } referencePathsShortUnique = null; referencePathsShortest = null; - - serializedNodes.Clear(); - initialSerializedNodes.Clear(); } } @@ -349,13 +517,13 @@ namespace AssetUsageDetectorNamespace } // Calculate short unique paths that start with this node - public void CalculateShortUniquePaths( List currentPaths ) + public void CalculateShortUniquePaths( List currentPaths ) { CalculateShortUniquePaths( currentPaths, new List( 8 ), new List( 8 ) { -1 }, 0 ); } // Just some boring calculations to find the short unique paths recursively - private void CalculateShortUniquePaths( List shortestPaths, List currentPath, List currentPathIndices, int latestObjectIndexInPath ) + private void CalculateShortUniquePaths( List shortestPaths, List currentPath, List currentPathIndices, int latestObjectIndexInPath ) { int currentIndex = currentPath.Count; currentPath.Add( this ); @@ -390,7 +558,7 @@ namespace AssetUsageDetectorNamespace for( int i = latestObjectIndexInPath + 1, j = 0; i < currentPathIndices.Count; i++, j++ ) pathIndices[j] = currentPathIndices[i]; - shortestPaths.Add( new ReferenceHolder.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) ); + shortestPaths.Add( new SearchResultGroup.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) ); } } else @@ -410,11 +578,11 @@ namespace AssetUsageDetectorNamespace } // Draw all the paths that start with this node on GUI recursively - public void DrawOnGUIRecursively( string linkToPrevNodeDescription = null ) + public void DrawOnGUIRecursively( SearchResultDrawParameters parameters, string linkToPrevNodeDescription ) { GUILayout.BeginHorizontal(); - DrawOnGUI( linkToPrevNodeDescription ); + DrawOnGUI( parameters, linkToPrevNodeDescription ); if( links.Count > 0 ) { @@ -423,7 +591,7 @@ namespace AssetUsageDetectorNamespace for( int i = 0; i < links.Count; i++ ) { ReferenceNode next = links[i].targetNode; - next.DrawOnGUIRecursively( links[i].description ); + next.DrawOnGUIRecursively( parameters, links[i].description ); } GUILayout.EndVertical(); @@ -433,36 +601,27 @@ namespace AssetUsageDetectorNamespace } // Draw only this node on GUI - public void DrawOnGUI( string linkToPrevNodeDescription ) + public void DrawOnGUI( SearchResultDrawParameters parameters, string linkToPrevNodeDescription ) { - string label = GetNodeContent( linkToPrevNodeDescription ); + string label = string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ); if( GUILayout.Button( label, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_HEIGHT ) ) { // If a reference is clicked, highlight it (either on Hierarchy view or Project view) UnityObject.SelectInEditor(); } - if( AssetUsageDetector.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) ) - AssetUsageDetector.tooltip = label; - } - - // Get the string representation of this node - private string GetNodeContent( string linkToPrevNodeDescription = null ) - { - if( !string.IsNullOrEmpty( linkToPrevNodeDescription ) ) - return linkToPrevNodeDescription + "\n" + description; - - return description; + if( parameters.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) ) + parameters.tooltip = label; } // Serialize this node and its connected nodes recursively - public int SerializeRecursively( Dictionary nodeToIndex, List serializedNodes ) + public int SerializeRecursively( Dictionary nodeToIndex, List serializedNodes ) { int index; if( nodeToIndex.TryGetValue( this, out index ) ) return index; - ReferenceHolder.SerializableNode serializedNode = new ReferenceHolder.SerializableNode() + SearchResult.SerializableNode serializedNode = new SearchResult.SerializableNode() { instanceId = instanceId ?? 0, isUnityObject = instanceId.HasValue, @@ -489,7 +648,7 @@ namespace AssetUsageDetectorNamespace } // Deserialize this node and its links from the serialized data - public void Deserialize( ReferenceHolder.SerializableNode serializedNode, List allNodes ) + public void Deserialize( SearchResult.SerializableNode serializedNode, List allNodes ) { if( serializedNode.isUnityObject ) instanceId = serializedNode.instanceId; diff --git a/Plugins/AssetUsageDetector/Editor/ReferenceHolder.cs.meta b/Plugins/AssetUsageDetector/Editor/SearchResult.cs.meta similarity index 100% rename from Plugins/AssetUsageDetector/Editor/ReferenceHolder.cs.meta rename to Plugins/AssetUsageDetector/Editor/SearchResult.cs.meta diff --git a/Plugins/AssetUsageDetector/Editor/Utilities.cs b/Plugins/AssetUsageDetector/Editor/Utilities.cs index 6f3befa..00502af 100644 --- a/Plugins/AssetUsageDetector/Editor/Utilities.cs +++ b/Plugins/AssetUsageDetector/Editor/Utilities.cs @@ -15,6 +15,8 @@ namespace AssetUsageDetectorNamespace typeof( Quaternion ), typeof( Color ), typeof( Color32 ), typeof( LayerMask ), typeof( Matrix4x4 ), typeof( AnimationCurve ), typeof( Gradient ), typeof( RectOffset ) }; + private static readonly HashSet folderContentsSet = new HashSet(); + public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true ); public static readonly GUILayoutOption GL_EXPAND_HEIGHT = GUILayout.ExpandHeight( true ); public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 ); @@ -23,7 +25,7 @@ namespace AssetUsageDetectorNamespace 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 ); - + private static GUIStyle m_boxGUIStyle; // GUIStyle used to draw the results of the search public static GUIStyle BoxGUIStyle { @@ -93,6 +95,30 @@ namespace AssetUsageDetectorNamespace return obj is Object && AssetDatabase.Contains( (Object) obj ); } + // Check if object is a folder asset + public static bool IsFolder( this Object obj ) + { + return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) ); + } + + // Returns an enumerator to iterate through all asset paths in the folder + public static IEnumerable EnumerateFolderContents( Object folderAsset ) + { + string[] folderContents = AssetDatabase.FindAssets( "", new string[] { AssetDatabase.GetAssetPath( folderAsset ) } ); + if( folderContents == null ) + return new EmptyEnumerator(); + + folderContentsSet.Clear(); + for( int i = 0; i < folderContents.Length; i++ ) + { + string filePath = AssetDatabase.GUIDToAssetPath( folderContents[i] ); + if( !string.IsNullOrEmpty( filePath ) && !AssetDatabase.IsValidFolder( filePath ) ) + folderContentsSet.Add( filePath ); + } + + return folderContentsSet; + } + // Select an object in the editor public static void SelectInEditor( this Object obj ) { @@ -269,5 +295,33 @@ namespace AssetUsageDetectorNamespace return null; } + + public static bool IsEmpty( this List objectsToSearch ) + { + if( objectsToSearch == null ) + return true; + + for( int i = 0; i < objectsToSearch.Count; i++ ) + { + if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) ) + return false; + } + + return true; + } + + public static bool IsEmpty( this List searchInAssetsSubset ) + { + if( searchInAssetsSubset == null ) + return true; + + for( int i = 0; i < searchInAssetsSubset.Count; i++ ) + { + if( searchInAssetsSubset[i] != null && !searchInAssetsSubset[i].Equals( null ) ) + return false; + } + + return true; + } } } \ No newline at end of file