From 541e33db89a5a0ea003ae21057ef0c86a96e4bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=BCleyman=20Yasir=20KULA?= Date: Thu, 2 Jul 2020 12:12:19 +0300 Subject: [PATCH] - Added Shader Graph support (will probably stop working after the serialization format changes: https://github.com/Unity-Technologies/Graphics/pull/222) - Added support for searching the "#include" lines in shader source codes (e.g. to find references to included .cginc files) - Default Texture/Object variables assigned to Shader and MonoScript assets via Inspector are now included in search - Split AssetUsageDetector class into multiple C# files so that it is easier to navigate to the desired variables/functions --- .../Editor/AssetUsageDetector.cs | 1019 +-------------- .../Editor/AssetUsageDetectorCache.cs | 182 +++ .../Editor/AssetUsageDetectorCache.cs.meta | 11 + .../AssetUsageDetectorSearchFunctions.cs | 1164 +++++++++++++++++ .../AssetUsageDetectorSearchFunctions.cs.meta | 11 + .../Editor/AssetUsageDetectorWindow.cs | 11 +- .../AssetUsageDetector/Editor/Utilities.cs | 61 +- package.json | 2 +- 8 files changed, 1483 insertions(+), 978 deletions(-) create mode 100644 Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs create mode 100644 Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs.meta create mode 100644 Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs create mode 100644 Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs.meta diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs index e998964..74ee259 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs @@ -2,29 +2,13 @@ using UnityEngine; using UnityEditor; -using UnityEditor.Animations; using UnityEngine.SceneManagement; using UnityEditor.SceneManagement; -using System.Collections; using System.Collections.Generic; using System.Reflection; using System; using System.IO; -using UnityEngine.UI; using System.Text; -#if UNITY_2017_1_OR_NEWER -using UnityEngine.U2D; -using UnityEngine.Playables; -#endif -#if UNITY_2018_2_OR_NEWER -using UnityEditor.U2D; -#endif -#if UNITY_2017_3_OR_NEWER -using UnityEditor.Compilation; -#endif -#if UNITY_2017_2_OR_NEWER -using UnityEngine.Tilemaps; -#endif using Object = UnityEngine.Object; namespace AssetUsageDetectorNamespace @@ -33,7 +17,7 @@ namespace AssetUsageDetectorNamespace public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 }; public enum PathDrawingMode { Full = 0, ShortRelevantParts = 1, Shortest = 2 }; - public class AssetUsageDetector + public partial class AssetUsageDetector { #region Helper Classes [Serializable] @@ -59,118 +43,32 @@ namespace AssetUsageDetectorNamespace public bool noAssetDatabaseChanges = false; public bool showDetailedProgressBar = false; } - - private class CacheEntry - { - public enum Result { Unknown = 0, No = 1, Yes = 2 }; - - public string hash; - public string[] dependencies; - public long[] fileSizes; - - public bool verified; - public Result searchResult; - - public CacheEntry( string path ) - { - Verify( path ); - } - - public CacheEntry( string hash, string[] dependencies, long[] fileSizes ) - { - this.hash = hash; - this.dependencies = dependencies; - this.fileSizes = fileSizes; - } - - public void Verify( string path ) - { - string hash = AssetDatabase.GetAssetDependencyHash( path ).ToString(); - if( this.hash != hash ) - { - this.hash = hash; - Refresh( path ); - } - - verified = true; - } - - public void Refresh( string path ) - { - dependencies = AssetDatabase.GetDependencies( path, false ); - if( fileSizes == null || fileSizes.Length != dependencies.Length ) - fileSizes = new long[dependencies.Length]; - - for( int i = 0; i < dependencies.Length; i++ ) - { - FileInfo assetFile = new FileInfo( dependencies[i] ); - fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L; - } - } - } - -#if UNITY_2017_3_OR_NEWER -#pragma warning disable 0649 // The fields' values are assigned via JsonUtility - [Serializable] - private struct AssemblyDefinitionReferences - { - public string reference; // Used by AssemblyDefinitionReferenceAssets - public List references; // Used by AssemblyDefinitionAssets - } -#pragma warning restore 0649 -#endif #endregion // A set that contains the searched asset(s) and their sub-assets (if any) private readonly HashSet objectsToSearchSet = new HashSet(); - - // Scene object(s) in objectsToSearchSet - private readonly HashSet sceneObjectsToSearchSet = new HashSet(); - // sceneObjectsToSearchSet's scene(s) + // Scenes of scene object(s) in objectsToSearchSet private readonly HashSet sceneObjectsToSearchScenesSet = new HashSet(); - // Project asset(s) in objectsToSearchSet private readonly HashSet assetsToSearchSet = new HashSet(); // assetsToSearchSet's path(s) private readonly HashSet assetsToSearchPathsSet = new HashSet(); - // The root prefab objects in assetsToSearch that will be used to search for prefab references + // The root prefab objects in assetsToSearchSet that will be used to search for prefab references private readonly List assetsToSearchRootPrefabs = new List( 4 ); // Path(s) of the assets that should be excluded from the search private readonly HashSet excludedAssetsPathsSet = new HashSet(); - -#if UNITY_2017_3_OR_NEWER - // Path(s) of the Assembly Definition Files in objectsToSearchSet (Value: files themselves) - private readonly Dictionary assemblyDefinitionFilesToSearch = new Dictionary( 8 ); -#endif + // Extension(s) of assets that will always be searched in detail + private readonly HashSet alwaysSearchedExtensionsSet = new HashSet(); // Results for the currently searched scene private SearchResultGroup currentSearchResultGroup; - // An optimization to fetch & filter fields and properties of a class only once - private readonly Dictionary typeToVariables = new Dictionary( 4096 ); // An optimization to search an object only once (key is a hash of the searched object) private readonly Dictionary searchedObjects = new Dictionary( 32768 ); - // An optimization to fetch an animation clip's curve bindings only once - private readonly Dictionary animationClipUniqueBindings = new Dictionary( 256 ); - // An optimization to fetch the dependencies of an asset only once (key is the path of the asset) - private Dictionary assetDependencyCache; - private CacheEntry lastRefreshedCacheEntry; - - // Dictionary to quickly find the function to search a specific type with - private Dictionary> typeToSearchFunction; // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function) private readonly List callStack = new List( 64 ); - private bool searchPrefabConnections; - private bool searchMonoBehavioursForScript; - private bool searchRenderers; - private bool searchMaterialsForShader; - private bool searchMaterialsForTexture; - - private bool searchSerializableVariablesOnly; - private bool prevSearchSerializableVariablesOnly; - private int searchDepthLimit; // Depth limit for recursively searching variables of objects private Object currentSearchedObject; @@ -185,16 +83,10 @@ namespace AssetUsageDetectorNamespace private GameObject openPrefabStagePrefabAsset; #endif - private BindingFlags fieldModifiers, propertyModifiers; - private BindingFlags prevFieldModifiers, prevPropertyModifiers; - private int searchedObjectsCount; // Number of searched objects private double searchStartTime; private readonly List nodesPool = new List( 32 ); - private readonly List validVariables = new List( 32 ); - - private string CachePath { get { return Application.dataPath + "/../Library/AssetUsageDetector.cache"; } } // Path of the cache file // Search for references! public SearchResult Run( Parameters searchParameters ) @@ -247,37 +139,33 @@ namespace AssetUsageDetectorNamespace // Get the scenes that are open right now SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null; - // Make sure the AssetDatabase is up-to-date + // Make sure that the AssetDatabase is up-to-date AssetDatabase.SaveAssets(); try { + // Initialize commonly used variables + searchResult = new List(); // Overall search results + + currentSearchedObject = null; currentDepth = 0; searchedObjectsCount = 0; searchStartTime = EditorApplication.timeSinceStartup; - this.fieldModifiers = searchParameters.fieldModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; - this.propertyModifiers = searchParameters.propertyModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; - this.searchDepthLimit = searchParameters.searchDepthLimit; - this.searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables; - this.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; - - // Initialize commonly used variables - searchResult = new List(); // Overall search results - - if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers || prevSearchSerializableVariablesOnly != searchSerializableVariablesOnly ) - typeToVariables.Clear(); + searchDepthLimit = searchParameters.searchDepthLimit; + dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; searchedObjects.Clear(); animationClipUniqueBindings.Clear(); callStack.Clear(); objectsToSearchSet.Clear(); - sceneObjectsToSearchSet.Clear(); sceneObjectsToSearchScenesSet.Clear(); assetsToSearchSet.Clear(); assetsToSearchPathsSet.Clear(); assetsToSearchRootPrefabs.Clear(); excludedAssetsPathsSet.Clear(); + alwaysSearchedExtensionsSet.Clear(); + shaderIncludesToSearchSet.Clear(); #if UNITY_2017_3_OR_NEWER assemblyDefinitionFilesToSearch.Clear(); #endif @@ -298,42 +186,6 @@ namespace AssetUsageDetectorNamespace lastRefreshedCacheEntry = null; - if( typeToSearchFunction == null ) - { - typeToSearchFunction = new Dictionary>() - { - { typeof( GameObject ), SearchGameObject }, - { typeof( Material ), SearchMaterial }, - { typeof( RuntimeAnimatorController ), SearchAnimatorController }, - { typeof( AnimatorOverrideController ), SearchAnimatorController }, - { typeof( AnimatorController ), SearchAnimatorController }, - { typeof( AnimatorStateMachine ), SearchAnimatorStateMachine }, - { typeof( AnimatorState ), SearchAnimatorState }, - { typeof( AnimatorStateTransition ), SearchAnimatorStateTransition }, - { typeof( BlendTree ), SearchBlendTree }, - { typeof( AnimationClip ), SearchAnimationClip }, -#if UNITY_2017_1_OR_NEWER - { typeof( SpriteAtlas ), SearchSpriteAtlas }, -#endif -#if UNITY_2017_3_OR_NEWER - { typeof( UnityEditorInternal.AssemblyDefinitionAsset ), SearchAssemblyDefinitionFile }, -#endif -#if UNITY_2019_2_OR_NEWER - { typeof( UnityEditorInternal.AssemblyDefinitionReferenceAsset ), SearchAssemblyDefinitionFile }, -#endif - }; - } - - prevFieldModifiers = fieldModifiers; - prevPropertyModifiers = propertyModifiers; - prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly; - - 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 ) @@ -350,7 +202,7 @@ namespace AssetUsageDetectorNamespace foreach( string filePath in folderContentsSet ) { // Skip scene assets - if( filePath.EndsWith( ".unity" ) ) + if( filePath.EndsWithFast( ".unity" ) ) continue; Object[] assets = AssetDatabase.LoadAllAssetsAtPath( filePath ); @@ -361,30 +213,19 @@ namespace AssetUsageDetectorNamespace AddSearchedObjectToFilteredSets( assets[i], true ); } - foreach( Object obj in objectsToSearchSet ) + // Find Project Settings to search for references. Don't search Project Settings if searched object(s) are all scene objects + // as Project Settings can't hold references to scene objects + string[] projectSettingsToSearch = new string[0]; + if( searchParameters.searchInProjectSettings && assetsToSearchSet.Count > 0 ) { - 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; - } + string[] projectSettingsAssets = Directory.GetFiles( "ProjectSettings" ); + projectSettingsToSearch = new string[projectSettingsAssets.Length]; + for( int i = 0; i < projectSettingsAssets.Length; i++ ) + projectSettingsToSearch[i] = "ProjectSettings/" + Path.GetFileName( projectSettingsAssets[i] ); + + // AssetDatabase.GetDependencies doesn't work with Project Settings assets. By adding these assets to assetsToSearchPathsSet, + // we make sure that AssetHasAnyReference returns true for these assets and they don't get excluded from the search + assetsToSearchPathsSet.UnionWith( projectSettingsToSearch ); } // Find the scenes to search for references @@ -468,16 +309,8 @@ namespace AssetUsageDetectorNamespace } ); } - // Find Project Settings to search for references - // Don't search Project Settings if searched object(s) are all scene objects as Project Settings can't hold references to scene objects - string[] projectSettingsToSearch = new string[0]; - if( searchParameters.searchInProjectSettings && assetsToSearchSet.Count > 0 ) - { - string[] projectSettingsFiles = Directory.GetFiles( "ProjectSettings" ); - projectSettingsToSearch = new string[projectSettingsFiles.Length]; - for( int i = 0; i < projectSettingsFiles.Length; i++ ) - projectSettingsToSearch[i] = "ProjectSettings/" + Path.GetFileName( projectSettingsFiles[i] ); - } + // Initialize data used by search functions + InitializeSearchFunctionsData( searchParameters ); // Initialize the nodes of searched asset(s) foreach( Object obj in objectsToSearchSet ) @@ -549,25 +382,6 @@ namespace AssetUsageDetectorNamespace } } -#if UNITY_2017_3_OR_NEWER - if( assemblyDefinitionFilesToSearch.Count > 0 ) - { - // AssetDatabase.GetDependencies doesn't return references from Assembly Definition Files to their Assembly Definition References, - // so if we are searching for an Assembly Definition File's usages, we must search all Assembly Definition Files' references - // manually. By adding all these files to assetsToSearchPathsSet, we make sure that AssetHasAnyReference returns true for - // these assets and they don't get excluded from the search - string[] assemblyDefinitionFilesGuids = AssetDatabase.FindAssets( "t:AssemblyDefinitionAsset" ); - for( int i = 0; i < assemblyDefinitionFilesGuids.Length; i++ ) - assetsToSearchPathsSet.Add( AssetDatabase.GUIDToAssetPath( assemblyDefinitionFilesGuids[i] ) ); - -#if UNITY_2019_2_OR_NEWER - assemblyDefinitionFilesGuids = AssetDatabase.FindAssets( "t:AssemblyDefinitionReferenceAsset" ); - for( int i = 0; i < assemblyDefinitionFilesGuids.Length; i++ ) - assetsToSearchPathsSet.Add( AssetDatabase.GUIDToAssetPath( assemblyDefinitionFilesGuids[i] ) ); -#endif - } -#endif - if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching assets", 0f ) ) throw new Exception( "Search aborted" ); @@ -580,7 +394,7 @@ namespace AssetUsageDetectorNamespace continue; // If asset resides inside the Assets directory and is not a scene asset - if( path.StartsWith( "Assets/" ) && !path.EndsWith( ".unity" ) ) + if( path.StartsWithFast( "Assets/" ) && !path.EndsWithFast( ".unity" ) ) { if( !AssetHasAnyReference( path ) ) continue; @@ -605,7 +419,7 @@ namespace AssetUsageDetectorNamespace searchResult.Add( currentSearchResultGroup ); } - // Search all assets inside ProjectSettings folder + // Search all assets inside the ProjectSettings folder if( projectSettingsToSearch.Length > 0 ) { currentSearchResultGroup = new SearchResultGroup( "Project Settings", SearchResultGroup.GroupType.ProjectSettings ); @@ -844,18 +658,9 @@ namespace AssetUsageDetectorNamespace if( shouldAddRootPrefabEntry ) assetsToSearchRootPrefabs.Add( go ); } -#if UNITY_2017_3_OR_NEWER - else if( obj is UnityEditorInternal.AssemblyDefinitionAsset ) - { - if( !string.IsNullOrEmpty( assetPath ) ) - assemblyDefinitionFilesToSearch[assetPath] = obj; - } -#endif } else { - sceneObjectsToSearchSet.Add( obj ); - if( obj is GameObject ) sceneObjectsToSearchScenesSet.Add( ( (GameObject) obj ).scene.path ); else if( obj is Component ) @@ -875,8 +680,6 @@ namespace AssetUsageDetectorNamespace if( isAsset ) assetsToSearchSet.Add( components[i] ); - else - sceneObjectsToSearchSet.Add( components[i] ); } } else if( obj is Component ) @@ -1005,6 +808,7 @@ namespace AssetUsageDetectorNamespace if( unityObject != null ) { // If the Object is an asset, search it in detail only if its dependencies contain at least one of the searched asset(s) + string assetPath = null; if( unityObject.IsAsset() ) { if( assetsToSearchSet.Count == 0 ) @@ -1013,9 +817,8 @@ namespace AssetUsageDetectorNamespace return null; } - // AssetHasAnyReference always returns false for Project Settings assets, ignore its result for them - string assetPath = AssetDatabase.GetAssetPath( unityObject ); - if( !assetPath.StartsWith( "ProjectSettings/" ) && !AssetHasAnyReference( assetPath ) ) + assetPath = AssetDatabase.GetAssetPath( unityObject ); + if( !AssetHasAnyReference( assetPath ) ) { searchedObjects.Add( objHash, null ); return null; @@ -1025,9 +828,11 @@ namespace AssetUsageDetectorNamespace callStack.Add( unityObject ); // Search the Object in detail - Func func; - if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out func ) ) - result = func( unityObject ); + Func searchFunction; + if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) ) + result = searchFunction( unityObject ); + else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) ) + result = searchFunction( unityObject ); else if( unityObject is Component ) result = SearchComponent( unityObject ); else @@ -1077,632 +882,21 @@ namespace AssetUsageDetectorNamespace return result; } - private ReferenceNode SearchGameObject( Object unityObject ) - { - GameObject go = (GameObject) unityObject; - ReferenceNode referenceNode = PopReferenceNode( go ); - - // Check if this GameObject's prefab is one of the selected assets - if( searchPrefabConnections ) - { -#if UNITY_2018_3_OR_NEWER - Object prefab = PrefabUtility.GetCorrespondingObjectFromSource( go ); -#else - Object prefab = PrefabUtility.GetPrefabParent( go ); -#endif - if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab as GameObject ) ) - referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" ); - } - - // Search through all the components of the object - Component[] components = go.GetComponents(); - for( int i = 0; i < components.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( components[i] ) ); - - return referenceNode; - } - - private ReferenceNode SearchComponent( Object unityObject ) - { - Component component = (Component) unityObject; - - // Ignore Transform component (no object field to search for) - if( component is Transform ) - return null; - - ReferenceNode referenceNode = PopReferenceNode( component ); - - if( searchMonoBehavioursForScript && component is MonoBehaviour ) - { - // If a searched asset is script, check if this component is an instance of it - MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component ); - if( objectsToSearchSet.Contains( script ) ) - referenceNode.AddLinkTo( GetReferenceNode( script ) ); - } - else if( searchRenderers && component is Renderer ) - { - // If an asset is a shader, texture or material, and this component is a Renderer, - // search it for references - Material[] materials = ( (Renderer) component ).sharedMaterials; - for( int i = 0; i < materials.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( materials[i] ) ); - } - else if( component is Animation ) - { - // If this component is an Animation, search its animation clips for references - foreach( AnimationState anim in (Animation) component ) - referenceNode.AddLinkTo( SearchObject( anim.clip ) ); - - // Search the objects that are animated by this Animation component for references - SearchAnimatedObjects( referenceNode ); - } - else if( component is Animator ) - { - // If this component is an Animator, search its animation clips for references (via AnimatorController) - referenceNode.AddLinkTo( SearchObject( ( (Animator) component ).runtimeAnimatorController ) ); - - // Search the objects that are animated by this Animator component for references - SearchAnimatedObjects( referenceNode ); - } -#if UNITY_2017_2_OR_NEWER - else if( component is Tilemap ) - { - // If this component is a Tilemap, search its tiles for references - TileBase[] tiles = new TileBase[( (Tilemap) component ).GetUsedTilesCount()]; - ( (Tilemap) component ).GetUsedTilesNonAlloc( tiles ); - - if( tiles != null ) - { - for( int i = 0; i < tiles.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( tiles[i] ), "Tile" ); - } - } -#endif -#if UNITY_2017_1_OR_NEWER - else if( component is PlayableDirector ) - { - // If this component is a PlayableDirectory, search its PlayableAsset's scene bindings for references - PlayableAsset playableAsset = ( (PlayableDirector) component ).playableAsset; - if( playableAsset != null && !playableAsset.Equals( null ) ) - { - foreach( PlayableBinding binding in playableAsset.outputs ) - referenceNode.AddLinkTo( SearchObject( ( (PlayableDirector) component ).GetGenericBinding( binding.sourceObject ) ), "Binding: " + binding.streamName ); - } - } -#endif - - SearchVariablesWithSerializedObject( referenceNode ); - return referenceNode; - } - - private ReferenceNode SearchMaterial( Object unityObject ) - { - Material material = (Material) unityObject; - ReferenceNode referenceNode = PopReferenceNode( material ); - - if( searchMaterialsForShader && objectsToSearchSet.Contains( material.shader ) ) - referenceNode.AddLinkTo( GetReferenceNode( material.shader ), "Shader" ); - - if( searchMaterialsForTexture ) - { - // Search through all the textures attached to this material - // Credit: http://answers.unity3d.com/answers/1116025/view.html - Shader shader = material.shader; - int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); - for( int i = 0; i < shaderPropertyCount; i++ ) - { - if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) - { - string propertyName = ShaderUtil.GetPropertyName( shader, i ); - Texture assignedTexture = material.GetTexture( propertyName ); - if( objectsToSearchSet.Contains( assignedTexture ) ) - referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName ); - } - } - } - - return referenceNode; - } - - private ReferenceNode SearchAnimatorController( Object unityObject ) - { - RuntimeAnimatorController controller = (RuntimeAnimatorController) unityObject; - ReferenceNode referenceNode = PopReferenceNode( controller ); - - if( controller is AnimatorController ) - { - AnimatorControllerLayer[] layers = ( (AnimatorController) controller ).layers; - for( int i = 0; i < layers.Length; i++ ) - { - if( objectsToSearchSet.Contains( layers[i].avatarMask ) ) - referenceNode.AddLinkTo( GetReferenceNode( layers[i].avatarMask ), layers[i].name + " Mask" ); - - referenceNode.AddLinkTo( SearchObject( layers[i].stateMachine ) ); - } - } - else - { - AnimationClip[] animClips = controller.animationClips; - for( int i = 0; i < animClips.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( animClips[i] ) ); - } - - return referenceNode; - } - - private ReferenceNode SearchAnimatorStateMachine( Object unityObject ) - { - AnimatorStateMachine animatorStateMachine = (AnimatorStateMachine) unityObject; - ReferenceNode referenceNode = PopReferenceNode( animatorStateMachine ); - - ChildAnimatorStateMachine[] stateMachines = animatorStateMachine.stateMachines; - for( int i = 0; i < stateMachines.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( stateMachines[i].stateMachine ), "Child State Machine" ); - - ChildAnimatorState[] states = animatorStateMachine.states; - for( int i = 0; i < states.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( states[i].state ) ); - - if( searchMonoBehavioursForScript ) - { - StateMachineBehaviour[] behaviours = animatorStateMachine.behaviours; - for( int i = 0; i < behaviours.Length; i++ ) - { - MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); - if( objectsToSearchSet.Contains( script ) ) - referenceNode.AddLinkTo( GetReferenceNode( script ) ); - } - } - - return referenceNode; - } - - private ReferenceNode SearchAnimatorState( Object unityObject ) - { - AnimatorState animatorState = (AnimatorState) unityObject; - ReferenceNode referenceNode = PopReferenceNode( animatorState ); - - referenceNode.AddLinkTo( SearchObject( animatorState.motion ), "Motion" ); - - if( searchMonoBehavioursForScript ) - { - StateMachineBehaviour[] behaviours = animatorState.behaviours; - for( int i = 0; i < behaviours.Length; i++ ) - { - MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); - if( objectsToSearchSet.Contains( script ) ) - referenceNode.AddLinkTo( GetReferenceNode( script ) ); - } - } - - return referenceNode; - } - - private ReferenceNode SearchAnimatorStateTransition( Object unityObject ) - { - // Don't search AnimatorStateTransition objects, it will just return duplicate results of SearchAnimatorStateMachine - return PopReferenceNode( unityObject ); - } - - private ReferenceNode SearchBlendTree( Object unityObject ) - { - BlendTree blendTree = (BlendTree) unityObject; - ReferenceNode referenceNode = PopReferenceNode( blendTree ); - - ChildMotion[] children = blendTree.children; - for( int i = 0; i < children.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( children[i].motion ), "Motion" ); - - return referenceNode; - } - - private ReferenceNode SearchAnimationClip( Object unityObject ) - { - AnimationClip clip = (AnimationClip) unityObject; - ReferenceNode referenceNode = PopReferenceNode( clip ); - - // Get all curves from animation clip - EditorCurveBinding[] objectCurves = AnimationUtility.GetObjectReferenceCurveBindings( clip ); - for( int i = 0; i < objectCurves.Length; i++ ) - { - // Search through all the keyframes in this curve - ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve( clip, objectCurves[i] ); - for( int j = 0; j < keyframes.Length; j++ ) - referenceNode.AddLinkTo( SearchObject( keyframes[j].value ), "Keyframe: " + keyframes[j].time ); - } - - // Get all events from animation clip - AnimationEvent[] events = AnimationUtility.GetAnimationEvents( clip ); - for( int i = 0; i < events.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( events[i].objectReferenceParameter ), "AnimationEvent: " + events[i].time ); - - return referenceNode; - } - -#if UNITY_2017_1_OR_NEWER - private ReferenceNode SearchSpriteAtlas( Object unityObject ) - { - SpriteAtlas spriteAtlas = (SpriteAtlas) unityObject; - ReferenceNode referenceNode = PopReferenceNode( spriteAtlas ); - - SerializedObject spriteAtlasSO = new SerializedObject( spriteAtlas ); - if( spriteAtlas.isVariant ) - { - Object masterAtlas = spriteAtlasSO.FindProperty( "m_MasterAtlas" ).objectReferenceValue; - if( objectsToSearchSet.Contains( masterAtlas ) ) - referenceNode.AddLinkTo( SearchObject( masterAtlas ), "Master Atlas" ); - } - -#if UNITY_2018_2_OR_NEWER - Object[] packables = spriteAtlas.GetPackables(); - if( packables != null ) - { - for( int i = 0; i < packables.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( packables[i] ), "Packed Texture" ); - } -#else - SerializedProperty packables = spriteAtlasSO.FindProperty( "m_EditorData.packables" ); - if( packables != null ) - { - for( int i = 0, length = packables.arraySize; i < length; i++ ) - referenceNode.AddLinkTo( SearchObject( packables.GetArrayElementAtIndex( i ).objectReferenceValue ), "Packed Texture" ); - } -#endif - - return referenceNode; - } -#endif - -#if UNITY_2017_3_OR_NEWER - // Find references from an Assembly Definition File to its Assembly Definition References - private ReferenceNode SearchAssemblyDefinitionFile( Object unityObject ) - { - if( assemblyDefinitionFilesToSearch.Count == 0 ) - return null; - - AssemblyDefinitionReferences assemblyDefinitionFile = JsonUtility.FromJson( ( (TextAsset) unityObject ).text ); - ReferenceNode referenceNode = PopReferenceNode( unityObject ); - - if( !string.IsNullOrEmpty( assemblyDefinitionFile.reference ) ) - { - if( assemblyDefinitionFile.references == null ) - assemblyDefinitionFile.references = new List( 1 ) { assemblyDefinitionFile.reference }; - else - assemblyDefinitionFile.references.Add( assemblyDefinitionFile.reference ); - } - - if( assemblyDefinitionFile.references != null ) - { - for( int i = 0; i < assemblyDefinitionFile.references.Count; i++ ) - { -#if UNITY_2019_1_OR_NEWER - string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference( assemblyDefinitionFile.references[i] ); -#else - string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName( assemblyDefinitionFile.references[i] ); -#endif - Object searchedAssemblyDefinitionFile; - if( assemblyDefinitionFilesToSearch.TryGetValue( assemblyPath, out searchedAssemblyDefinitionFile ) ) - referenceNode.AddLinkTo( GetReferenceNode( searchedAssemblyDefinitionFile ), "Referenced Assembly" ); - } - } - - return referenceNode; - } -#endif - - // Find references from an Animation/Animator component to the objects that it animates - private void SearchAnimatedObjects( ReferenceNode referenceNode ) - { - GameObject root = ( (Component) referenceNode.nodeObject ).gameObject; - AnimationClip[] clips = AnimationUtility.GetAnimationClips( root ); - for( int i = 0; i < clips.Length; i++ ) - { - AnimationClip clip = clips[i]; - bool isClipUnique = true; - for( int j = i - 1; j >= 0; j-- ) - { - if( clips[j] == clip ) - { - isClipUnique = false; - break; - } - } - - if( !isClipUnique ) - continue; - - EditorCurveBinding[] uniqueBindings; - if( !animationClipUniqueBindings.TryGetValue( clip, out uniqueBindings ) ) - { - // Calculate all the "unique" paths that the animation clip's curves have - // Both float curves (GetCurveBindings) and object reference curves (GetObjectReferenceCurveBindings) are checked - List _uniqueBindings = new List( 2 ); - EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings( clip ); - for( int j = 0; j < bindings.Length; j++ ) - { - string bindingPath = bindings[j].path; - if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object - continue; - - bool isBindingUnique = true; - for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) - { - if( bindingPath == _uniqueBindings[k].path ) - { - isBindingUnique = false; - break; - } - } - - if( isBindingUnique ) - _uniqueBindings.Add( bindings[j] ); - } - - bindings = AnimationUtility.GetObjectReferenceCurveBindings( clip ); - for( int j = 0; j < bindings.Length; j++ ) - { - string bindingPath = bindings[j].path; - if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object - continue; - - bool isBindingUnique = true; - for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) - { - if( bindingPath == _uniqueBindings[k].path ) - { - isBindingUnique = false; - break; - } - } - - if( isBindingUnique ) - _uniqueBindings.Add( bindings[j] ); - } - - uniqueBindings = _uniqueBindings.ToArray(); - animationClipUniqueBindings[clip] = uniqueBindings; - } - - string clipName = clip.name; - for( int j = 0; j < uniqueBindings.Length; j++ ) - referenceNode.AddLinkTo( SearchObject( AnimationUtility.GetAnimatedObject( root, uniqueBindings[j] ) ), "Animated via clip: " + clipName ); - } - } - - // Search through variables of an object with SerializedObject - private void SearchVariablesWithSerializedObject( ReferenceNode referenceNode ) - { - if( !isInPlayMode || referenceNode.nodeObject.IsAsset() ) - { - SerializedObject so = new SerializedObject( (Object) referenceNode.nodeObject ); - SerializedProperty iterator = so.GetIterator(); - if( iterator.NextVisible( true ) ) - { - bool enterChildren; - do - { - ReferenceNode searchResult; - switch( iterator.propertyType ) - { - case SerializedPropertyType.ObjectReference: - searchResult = SearchObject( iterator.objectReferenceValue ); - enterChildren = false; - break; - case SerializedPropertyType.ExposedReference: - searchResult = SearchObject( iterator.exposedReferenceValue ); - enterChildren = false; - break; - case SerializedPropertyType.Generic: - searchResult = null; - enterChildren = true; - break; - default: - searchResult = null; - enterChildren = false; - break; - } - - if( searchResult != null && searchResult != referenceNode ) - { - string propertyPath = iterator.propertyPath; - - // m_RD.texture is a redundant reference that shows up when searching sprites - if( !propertyPath.EndsWith( "m_RD.texture", StringComparison.Ordinal ) ) - referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath ); - } - } while( iterator.NextVisible( enterChildren ) ); - - return; - } - } - - // Use reflection algorithm as fallback - SearchVariablesWithReflection( referenceNode ); - } - - // Search through variables of an object with reflection - private void SearchVariablesWithReflection( ReferenceNode referenceNode ) - { - // Get filtered variables for this object - VariableGetterHolder[] variables = GetFilteredVariablesForType( referenceNode.nodeObject.GetType() ); - for( int i = 0; i < variables.Length; i++ ) - { - // When possible, don't search non-serializable variables - if( searchSerializableVariablesOnly && !variables[i].isSerializable ) - continue; - - try - { - object variableValue = variables[i].Get( referenceNode.nodeObject ); - if( variableValue == null ) - continue; - - // Values stored inside ICollection objects are searched using IEnumerable, - // no need to have duplicate search entries - if( !( variableValue is ICollection ) ) - { - ReferenceNode searchResult = SearchObject( variableValue ); - if( searchResult != null && searchResult != referenceNode ) - referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name ); - } - - if( variableValue is IEnumerable && !( variableValue is Transform ) ) - { - // 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 - int index = 0; - foreach( object element in (IEnumerable) variableValue ) - { - ReferenceNode searchResult = SearchObject( element ); - if( searchResult != null && searchResult != referenceNode ) - referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) ); - - index++; - } - } - } - catch( UnassignedReferenceException ) { } - catch( MissingReferenceException ) { } - catch( MissingComponentException ) { } - catch( NotImplementedException ) { } - } - } - - // Get filtered variables for a type - private VariableGetterHolder[] GetFilteredVariablesForType( Type type ) - { - VariableGetterHolder[] result; - if( typeToVariables.TryGetValue( type, out result ) ) - return result; - - // This is the first time this type of object is seen, filter and cache its variables - // Variable filtering process: - // 1- skip Obsolete variables - // 2- skip primitive types, enums and strings - // 3- skip common Unity types that can't hold any references (e.g. Vector3, Rect, Color, Quaternion) - // - // P.S. IsIgnoredUnityType() extension function handles steps 2) and 3) - - validVariables.Clear(); - - // Filter the fields - if( fieldModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) - { - Type currType = type; - while( currType != typeof( object ) ) - { - FieldInfo[] fields = currType.GetFields( fieldModifiers ); - for( int i = 0; i < fields.Length; i++ ) - { - FieldInfo field = fields[i]; - - // Skip obsolete fields - if( Attribute.IsDefined( field, typeof( ObsoleteAttribute ) ) ) - continue; - - // Skip primitive types - if( field.FieldType.IsIgnoredUnityType() ) - continue; - - // Additional filtering for fields: - // 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components - string fieldName = field.Name; - if( typeof( Graphic ).IsAssignableFrom( currType ) && - ( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) ) - continue; - - VariableGetVal getter = field.CreateGetter( type ); - if( getter != null ) - validVariables.Add( new VariableGetterHolder( field, getter, searchSerializableVariablesOnly ? field.IsSerializable() : true ) ); - } - - currType = currType.BaseType; - } - } - - if( propertyModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) - { - Type currType = type; - while( currType != typeof( object ) ) - { - PropertyInfo[] properties = currType.GetProperties( propertyModifiers ); - for( int i = 0; i < properties.Length; i++ ) - { - PropertyInfo property = properties[i]; - - // Skip obsolete properties - if( Attribute.IsDefined( property, typeof( ObsoleteAttribute ) ) ) - continue; - - // Skip primitive types - if( property.PropertyType.IsIgnoredUnityType() ) - continue; - - // Skip properties without a getter function - MethodInfo propertyGetter = property.GetGetMethod( true ); - if( propertyGetter == null ) - continue; - - // Skip indexer properties - if( property.GetIndexParameters().Length > 0 ) - continue; - - // No need to check properties with 'override' keyword - if( propertyGetter.GetBaseDefinition().DeclaringType != propertyGetter.DeclaringType ) - continue; - - // Additional filtering for properties: - // 1- Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of Component's to get more useful results - // 2- Ignore "canvasRenderer" and "canvas" properties of Graphic components - // 3 & 4- Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak) - string propertyName = property.Name; - if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" || - propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) ) - continue; - else if( typeof( Graphic ).IsAssignableFrom( currType ) && - ( propertyName == "canvasRenderer" || propertyName == "canvas" ) ) - continue; - else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" ) - continue; - else if( typeof( Renderer ).IsAssignableFrom( currType ) && - ( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) ) - continue; - else if( ( propertyName == "material" || propertyName == "materials" ) && - ( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) || -#if !UNITY_2019_3_OR_NEWER -#pragma warning disable 0618 - typeof( GUIText ).IsAssignableFrom( currType ) || -#pragma warning restore 0618 -#endif - typeof( Collider2D ).IsAssignableFrom( currType ) ) ) - continue; - else - { - VariableGetVal getter = property.CreateGetter(); - if( getter != null ) - validVariables.Add( new VariableGetterHolder( property, getter, searchSerializableVariablesOnly ? property.IsSerializable() : true ) ); - } - } - - currType = currType.BaseType; - } - } - - result = validVariables.ToArray(); - - // Cache the filtered fields - typeToVariables.Add( type, result ); - - return result; - } - // Check if the asset at specified path depends on any of the references private bool AssetHasAnyReference( string assetPath ) { - // "Find references of" assets can contain internal references if( assetsToSearchPathsSet.Contains( assetPath ) ) return true; + if( alwaysSearchedExtensionsSet.Count > 0 && alwaysSearchedExtensionsSet.Contains( Utilities.GetFileExtension( assetPath ) ) ) + return true; + + return AssetHasAnyReferenceInternal( assetPath ); + } + + // Recursively check if the asset at specified path depends on any of the references + private bool AssetHasAnyReferenceInternal( string assetPath ) + { CacheEntry cacheEntry; if( !assetDependencyCache.TryGetValue( assetPath, out cacheEntry ) ) { @@ -1778,7 +972,7 @@ namespace AssetUsageDetectorNamespace cacheEntry.searchResult = CacheEntry.Result.Unknown; lastRefreshedCacheEntry = cacheEntry; - return AssetHasAnyReference( assetPath ); + return AssetHasAnyReferenceInternal( assetPath ); } } @@ -1791,7 +985,7 @@ namespace AssetUsageDetectorNamespace for( int i = 0; i < dependencies.Length; i++ ) { - if( AssetHasAnyReference( dependencies[i] ) ) + if( AssetHasAnyReferenceInternal( dependencies[i] ) ) { cacheEntry.searchResult = CacheEntry.Result.Yes; return true; @@ -1859,118 +1053,5 @@ namespace AssetUsageDetectorNamespace Object.DestroyImmediate( temp ); } } - - public void SaveCache() - { - if( assetDependencyCache == null ) - return; - - try - { - using( FileStream stream = new FileStream( CachePath, FileMode.Create ) ) - using( BinaryWriter writer = new BinaryWriter( stream ) ) - { - writer.Write( assetDependencyCache.Count ); - - foreach( var keyValuePair in assetDependencyCache ) - { - CacheEntry cacheEntry = keyValuePair.Value; - string[] dependencies = cacheEntry.dependencies; - long[] fileSizes = cacheEntry.fileSizes; - - writer.Write( keyValuePair.Key ); - writer.Write( cacheEntry.hash ); - writer.Write( dependencies.Length ); - - for( int i = 0; i < dependencies.Length; i++ ) - { - writer.Write( dependencies[i] ); - writer.Write( fileSizes[i] ); - } - } - } - } - catch( Exception e ) - { - Debug.LogException( e ); - } - } - - private void LoadCache() - { - if( File.Exists( CachePath ) ) - { - using( FileStream stream = new FileStream( CachePath, FileMode.Open, FileAccess.Read ) ) - using( BinaryReader reader = new BinaryReader( stream ) ) - { - try - { - int cacheSize = reader.ReadInt32(); - assetDependencyCache = new Dictionary( cacheSize ); - - for( int i = 0; i < cacheSize; i++ ) - { - string assetPath = reader.ReadString(); - string hash = reader.ReadString(); - - int dependenciesLength = reader.ReadInt32(); - string[] dependencies = new string[dependenciesLength]; - long[] fileSizes = new long[dependenciesLength]; - for( int j = 0; j < dependenciesLength; j++ ) - { - dependencies[j] = reader.ReadString(); - fileSizes[j] = reader.ReadInt64(); - } - - assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies, fileSizes ); - } - } - catch( Exception e ) - { - assetDependencyCache = null; - Debug.LogWarning( "Couldn't load cache (probably cache format has changed in an update), will regenerate cache.\n" + e.ToString() ); - } - } - } - - // Generate cache for all assets for the first time - if( assetDependencyCache == null ) - { - assetDependencyCache = new Dictionary( 1024 * 8 ); - - string[] allAssets = AssetDatabase.GetAllAssetPaths(); - if( allAssets.Length > 0 ) - { - double startTime = EditorApplication.timeSinceStartup; - - try - { - for( int i = 0; i < allAssets.Length; i++ ) - { - if( i % 30 == 0 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Generating cache for the first time (optional)", (float) i / allAssets.Length ) ) - { - EditorUtility.ClearProgressBar(); - Debug.LogWarning( "Initial cache generation cancelled, cache will be generated on the fly as more and more assets are searched." ); - break; - } - - AssetHasAnyReference( allAssets[i] ); - } - - EditorUtility.ClearProgressBar(); - - Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" ); - Debug.Log( "You can always reset the cache by deleting " + Path.GetFullPath( CachePath ) ); - - SaveCache(); - } - catch( Exception e ) - { - EditorUtility.ClearProgressBar(); - Debug.LogException( e ); - } - } - } - } } } \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs new file mode 100644 index 0000000..c4171b5 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace AssetUsageDetectorNamespace +{ + public partial class AssetUsageDetector + { + #region Helper Classes + private class CacheEntry + { + public enum Result { Unknown = 0, No = 1, Yes = 2 }; + + public string hash; + public string[] dependencies; + public long[] fileSizes; + + public bool verified; + public Result searchResult; + + public CacheEntry( string path ) + { + Verify( path ); + } + + public CacheEntry( string hash, string[] dependencies, long[] fileSizes ) + { + this.hash = hash; + this.dependencies = dependencies; + this.fileSizes = fileSizes; + } + + public void Verify( string path ) + { + string hash = AssetDatabase.GetAssetDependencyHash( path ).ToString(); + if( this.hash != hash ) + { + this.hash = hash; + Refresh( path ); + } + + verified = true; + } + + public void Refresh( string path ) + { + dependencies = AssetDatabase.GetDependencies( path, false ); + if( fileSizes == null || fileSizes.Length != dependencies.Length ) + fileSizes = new long[dependencies.Length]; + + for( int i = 0; i < dependencies.Length; i++ ) + { + FileInfo assetFile = new FileInfo( dependencies[i] ); + fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L; + } + } + } + #endregion + + // An optimization to fetch the dependencies of an asset only once (key is the path of the asset) + private Dictionary assetDependencyCache; + private CacheEntry lastRefreshedCacheEntry; + + private string CachePath { get { return Application.dataPath + "/../Library/AssetUsageDetector.cache"; } } // Path of the cache file + + public void SaveCache() + { + if( assetDependencyCache == null ) + return; + + try + { + using( FileStream stream = new FileStream( CachePath, FileMode.Create ) ) + using( BinaryWriter writer = new BinaryWriter( stream ) ) + { + writer.Write( assetDependencyCache.Count ); + + foreach( var keyValuePair in assetDependencyCache ) + { + CacheEntry cacheEntry = keyValuePair.Value; + string[] dependencies = cacheEntry.dependencies; + long[] fileSizes = cacheEntry.fileSizes; + + writer.Write( keyValuePair.Key ); + writer.Write( cacheEntry.hash ); + writer.Write( dependencies.Length ); + + for( int i = 0; i < dependencies.Length; i++ ) + { + writer.Write( dependencies[i] ); + writer.Write( fileSizes[i] ); + } + } + } + } + catch( Exception e ) + { + Debug.LogException( e ); + } + } + + private void LoadCache() + { + if( File.Exists( CachePath ) ) + { + using( FileStream stream = new FileStream( CachePath, FileMode.Open, FileAccess.Read ) ) + using( BinaryReader reader = new BinaryReader( stream ) ) + { + try + { + int cacheSize = reader.ReadInt32(); + assetDependencyCache = new Dictionary( cacheSize ); + + for( int i = 0; i < cacheSize; i++ ) + { + string assetPath = reader.ReadString(); + string hash = reader.ReadString(); + + int dependenciesLength = reader.ReadInt32(); + string[] dependencies = new string[dependenciesLength]; + long[] fileSizes = new long[dependenciesLength]; + for( int j = 0; j < dependenciesLength; j++ ) + { + dependencies[j] = reader.ReadString(); + fileSizes[j] = reader.ReadInt64(); + } + + assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies, fileSizes ); + } + } + catch( Exception e ) + { + assetDependencyCache = null; + Debug.LogWarning( "Couldn't load cache (probably cache format has changed in an update), will regenerate cache.\n" + e.ToString() ); + } + } + } + + // Generate cache for all assets for the first time + if( assetDependencyCache == null ) + { + assetDependencyCache = new Dictionary( 1024 * 8 ); + + string[] allAssets = AssetDatabase.GetAllAssetPaths(); + if( allAssets.Length > 0 ) + { + double startTime = EditorApplication.timeSinceStartup; + + try + { + for( int i = 0; i < allAssets.Length; i++ ) + { + if( i % 30 == 0 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Generating cache for the first time (optional)", (float) i / allAssets.Length ) ) + { + EditorUtility.ClearProgressBar(); + Debug.LogWarning( "Initial cache generation cancelled, cache will be generated on the fly as more and more assets are searched." ); + break; + } + + assetDependencyCache[allAssets[i]] = new CacheEntry( allAssets[i] ); + } + + EditorUtility.ClearProgressBar(); + + Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" ); + Debug.Log( "You can always reset the cache by deleting " + Path.GetFullPath( CachePath ) ); + + SaveCache(); + } + catch( Exception e ) + { + EditorUtility.ClearProgressBar(); + Debug.LogException( e ); + } + } + } + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs.meta b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs.meta new file mode 100644 index 0000000..3d8d896 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 71ea9a3fd0b82594d8130d882dbfc844 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs new file mode 100644 index 0000000..4fa22c8 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs @@ -0,0 +1,1164 @@ +using System; +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEditor.Animations; +using UnityEngine; +using UnityEngine.UI; +#if UNITY_2017_1_OR_NEWER +using UnityEngine.U2D; +using UnityEngine.Playables; +#endif +#if UNITY_2018_2_OR_NEWER +using UnityEditor.U2D; +#endif +#if UNITY_2017_3_OR_NEWER +using UnityEditor.Compilation; +#endif +#if UNITY_2017_2_OR_NEWER +using UnityEngine.Tilemaps; +#endif +using Object = UnityEngine.Object; + +namespace AssetUsageDetectorNamespace +{ + public partial class AssetUsageDetector + { + #region Helper Classes +#if UNITY_2017_3_OR_NEWER +#pragma warning disable 0649 // The fields' values are assigned via JsonUtility + [Serializable] + private struct AssemblyDefinitionReferences + { + public string reference; // Used by AssemblyDefinitionReferenceAssets + public List references; // Used by AssemblyDefinitionAssets + } +#pragma warning restore 0649 +#endif + +#if UNITY_2018_1_OR_NEWER +#pragma warning disable 0649 // The fields' values are assigned via JsonUtility + [Serializable] + private struct ShaderGraphReferences + { + [Serializable] + public struct JSONHolder + { + public string JSONnodeData; + } + + [Serializable] + public class TextureHolder + { + public string m_SerializedTexture; + public string m_SerializedCubemap; + public string m_Guid; + + public string GetTexturePath() + { + string guid = ExtractGUIDFromString( !string.IsNullOrEmpty( m_SerializedTexture ) ? m_SerializedTexture : m_SerializedCubemap ); + if( string.IsNullOrEmpty( guid ) ) + guid = m_Guid; + + return string.IsNullOrEmpty( guid ) ? null : AssetDatabase.GUIDToAssetPath( guid ); + } + } + + [Serializable] + public struct PropertyData + { + public string m_Name; + public string m_DefaultReferenceName; + public string m_OverrideReferenceName; + public TextureHolder m_Value; + + public string GetName() + { + if( !string.IsNullOrEmpty( m_OverrideReferenceName ) ) + return m_OverrideReferenceName; + if( !string.IsNullOrEmpty( m_DefaultReferenceName ) ) + return m_DefaultReferenceName; + if( !string.IsNullOrEmpty( m_Name ) ) + return m_Name; + + return "Property"; + } + } + + [Serializable] + public struct NodeData + { + public string m_Name; + public string m_FunctionSource; // Custom Function node's Source field + public string m_SerializedSubGraph; // Sub-graph node + public List m_SerializableSlots; + + public string GetSubGraphPath() + { + string guid = ExtractGUIDFromString( m_SerializedSubGraph ); + return string.IsNullOrEmpty( guid ) ? null : AssetDatabase.GUIDToAssetPath( guid ); + } + } + + [Serializable] + public struct NodeSlotData + { + public TextureHolder m_Texture; + public TextureHolder m_TextureArray; + public TextureHolder m_Cubemap; + + public string GetTexturePath() + { + if( m_Texture != null ) + return m_Texture.GetTexturePath(); + if( m_Cubemap != null ) + return m_Cubemap.GetTexturePath(); + if( m_TextureArray != null ) + return m_TextureArray.GetTexturePath(); + + return null; + } + } + + public List m_SerializedProperties; + public List m_SerializableNodes; + + // String can be in one of the following formats: + // "guid":"GUID_VALUE" + // "guid": "GUID_VALUE" + // "guid" : "GUID_VALUE" + private static string ExtractGUIDFromString( string str ) + { + if( !string.IsNullOrEmpty( str ) ) + { + int guidStartIndex = str.IndexOf( "\"guid\"" ); + if( guidStartIndex >= 0 ) + { + guidStartIndex += 6; + guidStartIndex = str.IndexOf( '"', guidStartIndex ); + if( guidStartIndex > 0 ) + { + guidStartIndex++; + + int guidEndIndex = str.IndexOf( '"', guidStartIndex ); + if( guidEndIndex > 0 ) + return str.Substring( guidStartIndex, guidEndIndex - guidStartIndex ); + } + } + } + + return null; + } + } +#pragma warning restore 0649 +#endif + #endregion + + // Dictionary to quickly find the function to search a specific type with + private Dictionary> typeToSearchFunction; + // Dictionary to associate special file extensions with their search functions + private Dictionary> extensionToSearchFunction; + + // An optimization to fetch & filter fields and properties of a class only once + private readonly Dictionary typeToVariables = new Dictionary( 4096 ); + private readonly List validVariables = new List( 32 ); + + // Path(s) of .cginc, .cg, .hlsl and .glslinc assets in assetsToSearchSet + private readonly HashSet shaderIncludesToSearchSet = new HashSet(); + +#if UNITY_2017_3_OR_NEWER + // Path(s) of the Assembly Definition Files in objectsToSearchSet (Value: files themselves) + private readonly Dictionary assemblyDefinitionFilesToSearch = new Dictionary( 8 ); +#endif + + // An optimization to fetch an animation clip's curve bindings only once + private readonly Dictionary animationClipUniqueBindings = new Dictionary( 256 ); + + private bool searchPrefabConnections; + private bool searchMonoBehavioursForScript; + private bool searchRenderers; + private bool searchMaterialsForShader; + private bool searchTextureReferences; +#if UNITY_2018_1_OR_NEWER + private bool searchShaderGraphsForSubGraphs; +#endif + + private bool searchSerializableVariablesOnly; + private bool prevSearchSerializableVariablesOnly; + + private BindingFlags fieldModifiers, propertyModifiers; + private BindingFlags prevFieldModifiers, prevPropertyModifiers; + + private void InitializeSearchFunctionsData( Parameters searchParameters ) + { + if( typeToSearchFunction == null ) + { + typeToSearchFunction = new Dictionary>() + { + { typeof( GameObject ), SearchGameObject }, + { typeof( Material ), SearchMaterial }, + { typeof( Shader ), SearchShader }, + { typeof( MonoScript ), SearchMonoScript }, + { typeof( RuntimeAnimatorController ), SearchAnimatorController }, + { typeof( AnimatorOverrideController ), SearchAnimatorController }, + { typeof( AnimatorController ), SearchAnimatorController }, + { typeof( AnimatorStateMachine ), SearchAnimatorStateMachine }, + { typeof( AnimatorState ), SearchAnimatorState }, + { typeof( AnimatorStateTransition ), SearchAnimatorStateTransition }, + { typeof( BlendTree ), SearchBlendTree }, + { typeof( AnimationClip ), SearchAnimationClip }, +#if UNITY_2017_1_OR_NEWER + { typeof( SpriteAtlas ), SearchSpriteAtlas }, +#endif + }; + } + + if( extensionToSearchFunction == null ) + { + extensionToSearchFunction = new Dictionary>() + { + { "compute", SearchShaderSecondaryAsset }, + { "cginc", SearchShaderSecondaryAsset }, + { "cg", SearchShaderSecondaryAsset }, + { "glslinc", SearchShaderSecondaryAsset }, + { "hlsl", SearchShaderSecondaryAsset }, +#if UNITY_2017_3_OR_NEWER + { "asmdef", SearchAssemblyDefinitionFile }, +#endif +#if UNITY_2019_2_OR_NEWER + { "asmref", SearchAssemblyDefinitionFile }, +#endif +#if UNITY_2018_1_OR_NEWER + { "shadergraph", SearchShaderGraph }, + { "shadersubgraph", SearchShaderGraph }, +#endif + }; + } + + fieldModifiers = searchParameters.fieldModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; + propertyModifiers = searchParameters.propertyModifiers | BindingFlags.Instance | BindingFlags.DeclaredOnly; + searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables; + + if( prevFieldModifiers != fieldModifiers || prevPropertyModifiers != propertyModifiers || prevSearchSerializableVariablesOnly != searchSerializableVariablesOnly ) + typeToVariables.Clear(); + + prevFieldModifiers = fieldModifiers; + prevPropertyModifiers = propertyModifiers; + prevSearchSerializableVariablesOnly = searchSerializableVariablesOnly; + + searchPrefabConnections = false; + searchMonoBehavioursForScript = false; + searchRenderers = false; + searchMaterialsForShader = false; + searchTextureReferences = false; +#if UNITY_2018_1_OR_NEWER + searchShaderGraphsForSubGraphs = false; +#endif + + foreach( Object obj in objectsToSearchSet ) + { + if( obj is Texture ) + { + searchRenderers = true; + searchTextureReferences = 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; +#if UNITY_2017_3_OR_NEWER + else if( obj is UnityEditorInternal.AssemblyDefinitionAsset ) + assemblyDefinitionFilesToSearch[AssetDatabase.GetAssetPath( obj )] = obj; +#endif + } + + foreach( string path in assetsToSearchPathsSet ) + { + string extension = Utilities.GetFileExtension( path ); + if( extension == "hlsl" || extension == "cginc" || extension == "cg" || extension == "glslinc" ) + shaderIncludesToSearchSet.Add( path ); +#if UNITY_2018_1_OR_NEWER + else if( extension == "shadersubgraph" ) + searchShaderGraphsForSubGraphs = true; +#endif + } + + // AssetDatabase.GetDependencies doesn't take #include lines in shader source codes into consideration. If we are searching for references + // of a potential #include target (shaderIncludesToSearchSet), we must search all shader assets and check their #include lines manually + if( shaderIncludesToSearchSet.Count > 0 ) + { + alwaysSearchedExtensionsSet.Add( "shader" ); + alwaysSearchedExtensionsSet.Add( "compute" ); + alwaysSearchedExtensionsSet.Add( "cginc" ); + alwaysSearchedExtensionsSet.Add( "cg" ); + alwaysSearchedExtensionsSet.Add( "glslinc" ); + alwaysSearchedExtensionsSet.Add( "hlsl" ); + } + +#if UNITY_2017_3_OR_NEWER + // AssetDatabase.GetDependencies doesn't return references from Assembly Definition Files to their Assembly Definition References, + // so if we are searching for an Assembly Definition File's usages, we must search all Assembly Definition Files' references manually. + if( assemblyDefinitionFilesToSearch.Count > 0 ) + { + alwaysSearchedExtensionsSet.Add( "asmdef" ); +#if UNITY_2019_2_OR_NEWER + alwaysSearchedExtensionsSet.Add( "asmref" ); +#endif + } +#endif + +#if UNITY_2018_1_OR_NEWER + // AssetDatabase.GetDependencies doesn't work with Shader Graph assets. We must search all Shader Graph assets in the following cases: + // searchTextureReferences: to find Texture references used in various nodes and properties + // searchShaderGraphsForSubGraphs: to find Shader Sub-graph references in other Shader Graph assets + // shaderIncludesToSearchSet: to find .cginc, .cg, .glslinc and .hlsl references used in Custom Function nodes + if( searchTextureReferences || searchShaderGraphsForSubGraphs || shaderIncludesToSearchSet.Count > 0 ) + { + alwaysSearchedExtensionsSet.Add( "shadergraph" ); + alwaysSearchedExtensionsSet.Add( "shadersubgraph" ); + } +#endif + } + + private ReferenceNode SearchGameObject( Object unityObject ) + { + GameObject go = (GameObject) unityObject; + ReferenceNode referenceNode = PopReferenceNode( go ); + + // Check if this GameObject's prefab is one of the selected assets + if( searchPrefabConnections ) + { +#if UNITY_2018_3_OR_NEWER + Object prefab = PrefabUtility.GetCorrespondingObjectFromSource( go ); +#else + Object prefab = PrefabUtility.GetPrefabParent( go ); +#endif + if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab as GameObject ) ) + referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" ); + } + + // Search through all the components of the object + Component[] components = go.GetComponents(); + for( int i = 0; i < components.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( components[i] ) ); + + return referenceNode; + } + + private ReferenceNode SearchComponent( Object unityObject ) + { + Component component = (Component) unityObject; + + // Ignore Transform component (no object field to search for) + if( component is Transform ) + return null; + + ReferenceNode referenceNode = PopReferenceNode( component ); + + if( searchMonoBehavioursForScript && component is MonoBehaviour ) + { + // If a searched asset is script, check if this component is an instance of it + MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component ); + if( objectsToSearchSet.Contains( script ) ) + referenceNode.AddLinkTo( GetReferenceNode( script ) ); + } + else if( searchRenderers && component is Renderer ) + { + // If an asset is a shader, texture or material, and this component is a Renderer, + // search it for references + Material[] materials = ( (Renderer) component ).sharedMaterials; + for( int i = 0; i < materials.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( materials[i] ) ); + } + else if( component is Animation ) + { + // If this component is an Animation, search its animation clips for references + foreach( AnimationState anim in (Animation) component ) + referenceNode.AddLinkTo( SearchObject( anim.clip ) ); + + // Search the objects that are animated by this Animation component for references + SearchAnimatedObjects( referenceNode ); + } + else if( component is Animator ) + { + // If this component is an Animator, search its animation clips for references (via AnimatorController) + referenceNode.AddLinkTo( SearchObject( ( (Animator) component ).runtimeAnimatorController ) ); + + // Search the objects that are animated by this Animator component for references + SearchAnimatedObjects( referenceNode ); + } +#if UNITY_2017_2_OR_NEWER + else if( component is Tilemap ) + { + // If this component is a Tilemap, search its tiles for references + TileBase[] tiles = new TileBase[( (Tilemap) component ).GetUsedTilesCount()]; + ( (Tilemap) component ).GetUsedTilesNonAlloc( tiles ); + + if( tiles != null ) + { + for( int i = 0; i < tiles.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( tiles[i] ), "Tile" ); + } + } +#endif +#if UNITY_2017_1_OR_NEWER + else if( component is PlayableDirector ) + { + // If this component is a PlayableDirectory, search its PlayableAsset's scene bindings for references + PlayableAsset playableAsset = ( (PlayableDirector) component ).playableAsset; + if( playableAsset != null && !playableAsset.Equals( null ) ) + { + foreach( PlayableBinding binding in playableAsset.outputs ) + referenceNode.AddLinkTo( SearchObject( ( (PlayableDirector) component ).GetGenericBinding( binding.sourceObject ) ), "Binding: " + binding.streamName ); + } + } +#endif + + SearchVariablesWithSerializedObject( referenceNode ); + return referenceNode; + } + + private ReferenceNode SearchMaterial( Object unityObject ) + { + Material material = (Material) unityObject; + ReferenceNode referenceNode = PopReferenceNode( material ); + + if( searchMaterialsForShader && objectsToSearchSet.Contains( material.shader ) ) + referenceNode.AddLinkTo( GetReferenceNode( material.shader ), "Shader" ); + + if( searchTextureReferences ) + { + // Search through all the textures attached to this material + // Credit: http://answers.unity3d.com/answers/1116025/view.html + Shader shader = material.shader; + int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); + for( int i = 0; i < shaderPropertyCount; i++ ) + { + if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) + { + string propertyName = ShaderUtil.GetPropertyName( shader, i ); + Texture assignedTexture = material.GetTexture( propertyName ); + if( objectsToSearchSet.Contains( assignedTexture ) ) + referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName ); + } + } + } + + return referenceNode; + } + + // Searches default Texture values assigned to shader properties, as well as #include references in shader source code + private ReferenceNode SearchShader( Object unityObject ) + { + Shader shader = (Shader) unityObject; + ReferenceNode referenceNode = PopReferenceNode( shader ); + + if( searchTextureReferences ) + { + ShaderImporter shaderImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as ShaderImporter; + if( shaderImporter != null ) + { + int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); + for( int i = 0; i < shaderPropertyCount; i++ ) + { + if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) + { + string propertyName = ShaderUtil.GetPropertyName( shader, i ); + Texture defaultTexture = shaderImporter.GetDefaultTexture( propertyName ); +#if UNITY_2018_1_OR_NEWER + if( !defaultTexture ) + defaultTexture = shaderImporter.GetNonModifiableTexture( propertyName ); +#endif + + if( objectsToSearchSet.Contains( defaultTexture ) ) + referenceNode.AddLinkTo( GetReferenceNode( defaultTexture ), "Default Texture: " + propertyName ); + } + } + } + } + + // Search shader source code for #include references + if( shaderIncludesToSearchSet.Count > 0 ) + SearchShaderSourceCodeForCGIncludes( referenceNode ); + + return referenceNode; + } + + // Searches .compute, .cginc, .cg, .hlsl and .glslinc assets for #include references + private ReferenceNode SearchShaderSecondaryAsset( Object unityObject ) + { + if( shaderIncludesToSearchSet.Count == 0 ) + return null; + + ReferenceNode referenceNode = PopReferenceNode( unityObject ); + SearchShaderSourceCodeForCGIncludes( referenceNode ); + return referenceNode; + } + + // Searches default UnityEngine.Object values assigned to script variables + private ReferenceNode SearchMonoScript( Object unityObject ) + { + MonoScript script = (MonoScript) unityObject; + Type scriptType = script.GetClass(); + if( scriptType == null || ( !scriptType.IsSubclassOf( typeof( MonoBehaviour ) ) && !scriptType.IsSubclassOf( typeof( ScriptableObject ) ) ) ) + return null; + + MonoImporter scriptImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as MonoImporter; + if( scriptImporter == null ) + return null; + + ReferenceNode referenceNode = PopReferenceNode( script ); + + VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType ); + for( int i = 0; i < variables.Length; i++ ) + { + if( variables[i].isSerializable && !variables[i].isProperty ) + { + Object defaultValue = scriptImporter.GetDefaultReference( variables[i].name ); + if( objectsToSearchSet.Contains( defaultValue ) ) + referenceNode.AddLinkTo( GetReferenceNode( defaultValue ), "Default Variable Value: " + variables[i].name ); + } + } + + return referenceNode; + } + + private ReferenceNode SearchAnimatorController( Object unityObject ) + { + RuntimeAnimatorController controller = (RuntimeAnimatorController) unityObject; + ReferenceNode referenceNode = PopReferenceNode( controller ); + + if( controller is AnimatorController ) + { + AnimatorControllerLayer[] layers = ( (AnimatorController) controller ).layers; + for( int i = 0; i < layers.Length; i++ ) + { + if( objectsToSearchSet.Contains( layers[i].avatarMask ) ) + referenceNode.AddLinkTo( GetReferenceNode( layers[i].avatarMask ), layers[i].name + " Mask" ); + + referenceNode.AddLinkTo( SearchObject( layers[i].stateMachine ) ); + } + } + else + { + AnimationClip[] animClips = controller.animationClips; + for( int i = 0; i < animClips.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( animClips[i] ) ); + } + + return referenceNode; + } + + private ReferenceNode SearchAnimatorStateMachine( Object unityObject ) + { + AnimatorStateMachine animatorStateMachine = (AnimatorStateMachine) unityObject; + ReferenceNode referenceNode = PopReferenceNode( animatorStateMachine ); + + ChildAnimatorStateMachine[] stateMachines = animatorStateMachine.stateMachines; + for( int i = 0; i < stateMachines.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( stateMachines[i].stateMachine ), "Child State Machine" ); + + ChildAnimatorState[] states = animatorStateMachine.states; + for( int i = 0; i < states.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( states[i].state ) ); + + if( searchMonoBehavioursForScript ) + { + StateMachineBehaviour[] behaviours = animatorStateMachine.behaviours; + for( int i = 0; i < behaviours.Length; i++ ) + { + MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); + if( objectsToSearchSet.Contains( script ) ) + referenceNode.AddLinkTo( GetReferenceNode( script ) ); + } + } + + return referenceNode; + } + + private ReferenceNode SearchAnimatorState( Object unityObject ) + { + AnimatorState animatorState = (AnimatorState) unityObject; + ReferenceNode referenceNode = PopReferenceNode( animatorState ); + + referenceNode.AddLinkTo( SearchObject( animatorState.motion ), "Motion" ); + + if( searchMonoBehavioursForScript ) + { + StateMachineBehaviour[] behaviours = animatorState.behaviours; + for( int i = 0; i < behaviours.Length; i++ ) + { + MonoScript script = MonoScript.FromScriptableObject( behaviours[i] ); + if( objectsToSearchSet.Contains( script ) ) + referenceNode.AddLinkTo( GetReferenceNode( script ) ); + } + } + + return referenceNode; + } + + private ReferenceNode SearchAnimatorStateTransition( Object unityObject ) + { + // Don't search AnimatorStateTransition objects, it will just return duplicate results of SearchAnimatorStateMachine + return PopReferenceNode( unityObject ); + } + + private ReferenceNode SearchBlendTree( Object unityObject ) + { + BlendTree blendTree = (BlendTree) unityObject; + ReferenceNode referenceNode = PopReferenceNode( blendTree ); + + ChildMotion[] children = blendTree.children; + for( int i = 0; i < children.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( children[i].motion ), "Motion" ); + + return referenceNode; + } + + private ReferenceNode SearchAnimationClip( Object unityObject ) + { + AnimationClip clip = (AnimationClip) unityObject; + ReferenceNode referenceNode = PopReferenceNode( clip ); + + // Get all curves from animation clip + EditorCurveBinding[] objectCurves = AnimationUtility.GetObjectReferenceCurveBindings( clip ); + for( int i = 0; i < objectCurves.Length; i++ ) + { + // Search through all the keyframes in this curve + ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve( clip, objectCurves[i] ); + for( int j = 0; j < keyframes.Length; j++ ) + referenceNode.AddLinkTo( SearchObject( keyframes[j].value ), "Keyframe: " + keyframes[j].time ); + } + + // Get all events from animation clip + AnimationEvent[] events = AnimationUtility.GetAnimationEvents( clip ); + for( int i = 0; i < events.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( events[i].objectReferenceParameter ), "AnimationEvent: " + events[i].time ); + + return referenceNode; + } + +#if UNITY_2017_1_OR_NEWER + private ReferenceNode SearchSpriteAtlas( Object unityObject ) + { + SpriteAtlas spriteAtlas = (SpriteAtlas) unityObject; + ReferenceNode referenceNode = PopReferenceNode( spriteAtlas ); + + SerializedObject spriteAtlasSO = new SerializedObject( spriteAtlas ); + if( spriteAtlas.isVariant ) + { + Object masterAtlas = spriteAtlasSO.FindProperty( "m_MasterAtlas" ).objectReferenceValue; + if( objectsToSearchSet.Contains( masterAtlas ) ) + referenceNode.AddLinkTo( SearchObject( masterAtlas ), "Master Atlas" ); + } + +#if UNITY_2018_2_OR_NEWER + Object[] packables = spriteAtlas.GetPackables(); + if( packables != null ) + { + for( int i = 0; i < packables.Length; i++ ) + referenceNode.AddLinkTo( SearchObject( packables[i] ), "Packed Texture" ); + } +#else + SerializedProperty packables = spriteAtlasSO.FindProperty( "m_EditorData.packables" ); + if( packables != null ) + { + for( int i = 0, length = packables.arraySize; i < length; i++ ) + referenceNode.AddLinkTo( SearchObject( packables.GetArrayElementAtIndex( i ).objectReferenceValue ), "Packed Texture" ); + } +#endif + + return referenceNode; + } +#endif + +#if UNITY_2017_3_OR_NEWER + // Find references from an Assembly Definition File to its Assembly Definition References + private ReferenceNode SearchAssemblyDefinitionFile( Object unityObject ) + { + if( assemblyDefinitionFilesToSearch.Count == 0 ) + return null; + + AssemblyDefinitionReferences assemblyDefinitionFile = JsonUtility.FromJson( ( (TextAsset) unityObject ).text ); + ReferenceNode referenceNode = PopReferenceNode( unityObject ); + + if( !string.IsNullOrEmpty( assemblyDefinitionFile.reference ) ) + { + if( assemblyDefinitionFile.references == null ) + assemblyDefinitionFile.references = new List( 1 ) { assemblyDefinitionFile.reference }; + else + assemblyDefinitionFile.references.Add( assemblyDefinitionFile.reference ); + } + + if( assemblyDefinitionFile.references != null ) + { + for( int i = 0; i < assemblyDefinitionFile.references.Count; i++ ) + { +#if UNITY_2019_1_OR_NEWER + string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference( assemblyDefinitionFile.references[i] ); +#else + string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName( assemblyDefinitionFile.references[i] ); +#endif + Object searchedAssemblyDefinitionFile; + if( assemblyDefinitionFilesToSearch.TryGetValue( assemblyPath, out searchedAssemblyDefinitionFile ) ) + referenceNode.AddLinkTo( GetReferenceNode( searchedAssemblyDefinitionFile ), "Referenced Assembly" ); + } + } + + return referenceNode; + } +#endif + +#if UNITY_2018_1_OR_NEWER + // Searches Shader Graph assets for references + private ReferenceNode SearchShaderGraph( Object unityObject ) + { + if( !searchTextureReferences && !searchShaderGraphsForSubGraphs && shaderIncludesToSearchSet.Count == 0 ) + return null; + + // Shader Graph assets are JSON files, they must be crawled manually to find references + ShaderGraphReferences shaderGraph = JsonUtility.FromJson( File.ReadAllText( AssetDatabase.GetAssetPath( unityObject ) ) ); + ReferenceNode referenceNode = PopReferenceNode( unityObject ); + + if( shaderGraph.m_SerializedProperties != null ) + { + for( int i = shaderGraph.m_SerializedProperties.Count - 1; i >= 0; i-- ) + { + string propertyJSON = shaderGraph.m_SerializedProperties[i].JSONnodeData; + if( string.IsNullOrEmpty( propertyJSON ) ) + continue; + + ShaderGraphReferences.PropertyData propertyData = JsonUtility.FromJson( propertyJSON ); + if( propertyData.m_Value == null ) + continue; + + string texturePath = propertyData.m_Value.GetTexturePath(); + if( string.IsNullOrEmpty( texturePath ) || !assetsToSearchPathsSet.Contains( texturePath ) ) + continue; + + Texture texture = AssetDatabase.LoadAssetAtPath( texturePath ); + if( objectsToSearchSet.Contains( texture ) ) + referenceNode.AddLinkTo( GetReferenceNode( texture ), "Default Texture: " + propertyData.GetName() ); + } + } + + if( shaderGraph.m_SerializableNodes != null ) + { + for( int i = shaderGraph.m_SerializableNodes.Count - 1; i >= 0; i-- ) + { + string nodeJSON = shaderGraph.m_SerializableNodes[i].JSONnodeData; + if( string.IsNullOrEmpty( nodeJSON ) ) + continue; + + ShaderGraphReferences.NodeData nodeData = JsonUtility.FromJson( nodeJSON ); + if( !string.IsNullOrEmpty( nodeData.m_FunctionSource ) ) + { + string customFunctionPath = AssetDatabase.GUIDToAssetPath( nodeData.m_FunctionSource ); + if( !string.IsNullOrEmpty( customFunctionPath ) && assetsToSearchPathsSet.Contains( customFunctionPath ) ) + { + Object customFunction = AssetDatabase.LoadMainAssetAtPath( customFunctionPath ); + if( objectsToSearchSet.Contains( customFunction ) ) + referenceNode.AddLinkTo( GetReferenceNode( customFunction ), "Used in node: " + nodeData.m_Name ); + } + } + + if( searchShaderGraphsForSubGraphs ) + { + string subGraphPath = nodeData.GetSubGraphPath(); + if( !string.IsNullOrEmpty( subGraphPath ) && assetsToSearchPathsSet.Contains( subGraphPath ) ) + { + Object subGraph = AssetDatabase.LoadMainAssetAtPath( subGraphPath ); + if( objectsToSearchSet.Contains( subGraph ) ) + referenceNode.AddLinkTo( GetReferenceNode( subGraph ), "Used as Sub-graph" ); + } + } + + if( nodeData.m_SerializableSlots == null ) + continue; + + for( int j = nodeData.m_SerializableSlots.Count - 1; j >= 0; j-- ) + { + string nodeSlotJSON = nodeData.m_SerializableSlots[j].JSONnodeData; + if( string.IsNullOrEmpty( nodeSlotJSON ) ) + continue; + + string texturePath = JsonUtility.FromJson( nodeSlotJSON ).GetTexturePath(); + if( string.IsNullOrEmpty( texturePath ) || !assetsToSearchPathsSet.Contains( texturePath ) ) + continue; + + Texture texture = AssetDatabase.LoadAssetAtPath( texturePath ); + if( objectsToSearchSet.Contains( texture ) ) + referenceNode.AddLinkTo( GetReferenceNode( texture ), "Used in node: " + nodeData.m_Name ); + } + } + } + + return referenceNode; + } +#endif + + // Find references from an Animation/Animator component to the objects that it animates + private void SearchAnimatedObjects( ReferenceNode referenceNode ) + { + GameObject root = ( (Component) referenceNode.nodeObject ).gameObject; + AnimationClip[] clips = AnimationUtility.GetAnimationClips( root ); + for( int i = 0; i < clips.Length; i++ ) + { + AnimationClip clip = clips[i]; + bool isClipUnique = true; + for( int j = i - 1; j >= 0; j-- ) + { + if( clips[j] == clip ) + { + isClipUnique = false; + break; + } + } + + if( !isClipUnique ) + continue; + + EditorCurveBinding[] uniqueBindings; + if( !animationClipUniqueBindings.TryGetValue( clip, out uniqueBindings ) ) + { + // Calculate all the "unique" paths that the animation clip's curves have + // Both float curves (GetCurveBindings) and object reference curves (GetObjectReferenceCurveBindings) are checked + List _uniqueBindings = new List( 2 ); + EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings( clip ); + for( int j = 0; j < bindings.Length; j++ ) + { + string bindingPath = bindings[j].path; + if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object + continue; + + bool isBindingUnique = true; + for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) + { + if( bindingPath == _uniqueBindings[k].path ) + { + isBindingUnique = false; + break; + } + } + + if( isBindingUnique ) + _uniqueBindings.Add( bindings[j] ); + } + + bindings = AnimationUtility.GetObjectReferenceCurveBindings( clip ); + for( int j = 0; j < bindings.Length; j++ ) + { + string bindingPath = bindings[j].path; + if( string.IsNullOrEmpty( bindingPath ) ) // Ignore the root animated object + continue; + + bool isBindingUnique = true; + for( int k = _uniqueBindings.Count - 1; k >= 0; k-- ) + { + if( bindingPath == _uniqueBindings[k].path ) + { + isBindingUnique = false; + break; + } + } + + if( isBindingUnique ) + _uniqueBindings.Add( bindings[j] ); + } + + uniqueBindings = _uniqueBindings.ToArray(); + animationClipUniqueBindings[clip] = uniqueBindings; + } + + string clipName = clip.name; + for( int j = 0; j < uniqueBindings.Length; j++ ) + referenceNode.AddLinkTo( SearchObject( AnimationUtility.GetAnimatedObject( root, uniqueBindings[j] ) ), "Animated via clip: " + clipName ); + } + } + + // Search #include references in shader source code + private void SearchShaderSourceCodeForCGIncludes( ReferenceNode referenceNode ) + { + string shaderPath = AssetDatabase.GetAssetPath( (Object) referenceNode.nodeObject ); + string shaderSource = File.ReadAllText( shaderPath ); + + int includeStartIndex, includeEndIndex = 0; + while( true ) + { + includeStartIndex = shaderSource.IndexOf( "#include ", includeEndIndex ); + if( includeStartIndex < 0 ) + return; + + includeStartIndex = shaderSource.IndexOf( '"', includeStartIndex + 9 ); + if( includeStartIndex < 0 ) + return; + + includeStartIndex++; + includeEndIndex = shaderSource.IndexOf( '"', includeStartIndex ); + if( includeEndIndex < 0 ) + return; + + if( includeEndIndex > includeStartIndex ) + { + string include = shaderSource.Substring( includeStartIndex, includeEndIndex - includeStartIndex ); + bool isIncludePotentialReference = shaderIncludesToSearchSet.Contains( include ); + if( !isIncludePotentialReference ) + { + // Get absolute path of the #include + include = Path.GetFullPath( Path.Combine( Path.GetDirectoryName( shaderPath ), include ) ); + + int trimStartLength = Directory.GetCurrentDirectory().Length + 1; // Convert absolute path to a Project-relative path + if( include.Length > trimStartLength ) + { + include = include.Substring( trimStartLength ).Replace( '\\', '/' ); + isIncludePotentialReference = shaderIncludesToSearchSet.Contains( include ); + } + } + + if( isIncludePotentialReference ) + { + Object cgShader = AssetDatabase.LoadMainAssetAtPath( include ); + if( objectsToSearchSet.Contains( cgShader ) ) + referenceNode.AddLinkTo( GetReferenceNode( cgShader ), "Used with #include" ); + } + } + } + } + + // Search through variables of an object with SerializedObject + private void SearchVariablesWithSerializedObject( ReferenceNode referenceNode ) + { + if( !isInPlayMode || referenceNode.nodeObject.IsAsset() ) + { + SerializedObject so = new SerializedObject( (Object) referenceNode.nodeObject ); + SerializedProperty iterator = so.GetIterator(); + if( iterator.NextVisible( true ) ) + { + bool enterChildren; + do + { + ReferenceNode searchResult; + switch( iterator.propertyType ) + { + case SerializedPropertyType.ObjectReference: + searchResult = SearchObject( iterator.objectReferenceValue ); + enterChildren = false; + break; + case SerializedPropertyType.ExposedReference: + searchResult = SearchObject( iterator.exposedReferenceValue ); + enterChildren = false; + break; + case SerializedPropertyType.Generic: + searchResult = null; + enterChildren = true; + break; + default: + searchResult = null; + enterChildren = false; + break; + } + + if( searchResult != null && searchResult != referenceNode ) + { + string propertyPath = iterator.propertyPath; + + // m_RD.texture is a redundant reference that shows up when searching sprites + if( !propertyPath.EndsWithFast( "m_RD.texture" ) ) + referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath ); + } + } while( iterator.NextVisible( enterChildren ) ); + + return; + } + } + + // Use reflection algorithm as fallback + SearchVariablesWithReflection( referenceNode ); + } + + // Search through variables of an object with reflection + private void SearchVariablesWithReflection( ReferenceNode referenceNode ) + { + // Get filtered variables for this object + VariableGetterHolder[] variables = GetFilteredVariablesForType( referenceNode.nodeObject.GetType() ); + for( int i = 0; i < variables.Length; i++ ) + { + // When possible, don't search non-serializable variables + if( searchSerializableVariablesOnly && !variables[i].isSerializable ) + continue; + + try + { + object variableValue = variables[i].Get( referenceNode.nodeObject ); + if( variableValue == null ) + continue; + + // Values stored inside ICollection objects are searched using IEnumerable, + // no need to have duplicate search entries + if( !( variableValue is ICollection ) ) + { + ReferenceNode searchResult = SearchObject( variableValue ); + if( searchResult != null && searchResult != referenceNode ) + referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name ); + } + + if( variableValue is IEnumerable && !( variableValue is Transform ) ) + { + // 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 + int index = 0; + foreach( object element in (IEnumerable) variableValue ) + { + ReferenceNode searchResult = SearchObject( element ); + if( searchResult != null && searchResult != referenceNode ) + referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) ); + + index++; + } + } + } + catch( UnassignedReferenceException ) { } + catch( MissingReferenceException ) { } + catch( MissingComponentException ) { } + catch( NotImplementedException ) { } + } + } + + // Get filtered variables for a type + private VariableGetterHolder[] GetFilteredVariablesForType( Type type ) + { + VariableGetterHolder[] result; + if( typeToVariables.TryGetValue( type, out result ) ) + return result; + + // This is the first time this type of object is seen, filter and cache its variables + // Variable filtering process: + // 1- skip Obsolete variables + // 2- skip primitive types, enums and strings + // 3- skip common Unity types that can't hold any references (e.g. Vector3, Rect, Color, Quaternion) + // + // P.S. IsIgnoredUnityType() extension function handles steps 2) and 3) + + validVariables.Clear(); + + // Filter the fields + if( fieldModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) + { + Type currType = type; + while( currType != typeof( object ) ) + { + FieldInfo[] fields = currType.GetFields( fieldModifiers ); + for( int i = 0; i < fields.Length; i++ ) + { + FieldInfo field = fields[i]; + + // Skip obsolete fields + if( Attribute.IsDefined( field, typeof( ObsoleteAttribute ) ) ) + continue; + + // Skip primitive types + if( field.FieldType.IsIgnoredUnityType() ) + continue; + + // Additional filtering for fields: + // 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components + string fieldName = field.Name; + if( typeof( Graphic ).IsAssignableFrom( currType ) && + ( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) ) + continue; + + VariableGetVal getter = field.CreateGetter( type ); + if( getter != null ) + validVariables.Add( new VariableGetterHolder( field, getter, searchSerializableVariablesOnly ? field.IsSerializable() : true ) ); + } + + currType = currType.BaseType; + } + } + + if( propertyModifiers != ( BindingFlags.Instance | BindingFlags.DeclaredOnly ) ) + { + Type currType = type; + while( currType != typeof( object ) ) + { + PropertyInfo[] properties = currType.GetProperties( propertyModifiers ); + for( int i = 0; i < properties.Length; i++ ) + { + PropertyInfo property = properties[i]; + + // Skip obsolete properties + if( Attribute.IsDefined( property, typeof( ObsoleteAttribute ) ) ) + continue; + + // Skip primitive types + if( property.PropertyType.IsIgnoredUnityType() ) + continue; + + // Skip properties without a getter function + MethodInfo propertyGetter = property.GetGetMethod( true ); + if( propertyGetter == null ) + continue; + + // Skip indexer properties + if( property.GetIndexParameters().Length > 0 ) + continue; + + // No need to check properties with 'override' keyword + if( propertyGetter.GetBaseDefinition().DeclaringType != propertyGetter.DeclaringType ) + continue; + + // Additional filtering for properties: + // 1- Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of Component's to get more useful results + // 2- Ignore "canvasRenderer" and "canvas" properties of Graphic components + // 3 & 4- Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak) + string propertyName = property.Name; + if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" || + propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) ) + continue; + else if( typeof( Graphic ).IsAssignableFrom( currType ) && + ( propertyName == "canvasRenderer" || propertyName == "canvas" ) ) + continue; + else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" ) + continue; + else if( typeof( Renderer ).IsAssignableFrom( currType ) && + ( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) ) + continue; + else if( ( propertyName == "material" || propertyName == "materials" ) && + ( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) || +#if !UNITY_2019_3_OR_NEWER +#pragma warning disable 0618 + typeof( GUIText ).IsAssignableFrom( currType ) || +#pragma warning restore 0618 +#endif + typeof( Collider2D ).IsAssignableFrom( currType ) ) ) + continue; + else + { + VariableGetVal getter = property.CreateGetter(); + if( getter != null ) + validVariables.Add( new VariableGetterHolder( property, getter, searchSerializableVariablesOnly ? property.IsSerializable() : true ) ); + } + } + + currType = currType.BaseType; + } + } + + result = validVariables.ToArray(); + + // Cache the filtered fields + typeToVariables.Add( type, result ); + + return result; + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs.meta b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs.meta new file mode 100644 index 0000000..fc1cd02 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93aaae685d4c3db44baeb91a0296855e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs index 928d5fb..3d21800 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs @@ -71,6 +71,9 @@ namespace AssetUsageDetectorNamespace private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false ); private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false ); + private readonly GUIContent restoreInitialSceneSetupLabel = new GUIContent( "Restore initial scene setup (Recommended)", "For example, if scene A was open when the search was started and scenes A and B are open after the search is completed, clicking the \"Reset Search\" button will automatically close scene B" ); + private readonly GUIContent showTooltipsLabel = new GUIContent( "Show tooltips", "Display nodes' contents in a tooltip when cursor hovers over them" ); + private Vector2 scrollPosition = Vector2.zero; private bool shouldRepositionSelf; @@ -371,7 +374,7 @@ namespace AssetUsageDetectorNamespace // If we are stuck at this phase, then we have encountered an exception GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." ); - restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup (Recommended)", restoreInitialSceneSetup ); + restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup ); if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) ) ReturnToSetupPhase( restoreInitialSceneSetup ); @@ -533,7 +536,7 @@ namespace AssetUsageDetectorNamespace GUILayout.Space( 10 ); GUI.enabled = true; - restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup after search is reset (Recommended)", restoreInitialSceneSetup ); + restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup ); if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) ) ReturnToSetupPhase( restoreInitialSceneSetup ); @@ -581,7 +584,7 @@ namespace AssetUsageDetectorNamespace //GUILayout.Space( 10 ); - searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( "Show tooltips", searchResultDrawParameters.showTooltips ); + searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( showTooltipsLabel, searchResultDrawParameters.showTooltips ); noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges ); searchResultDrawParameters.noAssetDatabaseChanges = noAssetDatabaseChanges; @@ -611,7 +614,7 @@ namespace AssetUsageDetectorNamespace GUILayout.Space( 35 ); - if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) ) + if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) ) searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest; GUILayout.EndHorizontal(); diff --git a/Plugins/AssetUsageDetector/Editor/Utilities.cs b/Plugins/AssetUsageDetector/Editor/Utilities.cs index a436731..7b389f8 100644 --- a/Plugins/AssetUsageDetector/Editor/Utilities.cs +++ b/Plugins/AssetUsageDetector/Editor/Utilities.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Text; #if UNITY_2018_1_OR_NEWER using Unity.Collections; #endif @@ -46,6 +47,8 @@ namespace AssetUsageDetectorNamespace private static readonly HashSet folderContentsSet = new HashSet(); + private static readonly StringBuilder stringBuilder = new StringBuilder( 10 ); + #if UNITY_2018_3_OR_NEWER private static int previousPingedPrefabInstanceId; private static double previousPingedPrefabPingTime; @@ -427,6 +430,34 @@ namespace AssetUsageDetectorNamespace return true; } + // Returns file extension in lowercase (period not included) + public static string GetFileExtension( string path ) + { + int extensionIndex = path.LastIndexOf( '.' ); + if( extensionIndex < 0 || extensionIndex >= path.Length - 1 ) + return ""; + + stringBuilder.Length = 0; + for( extensionIndex++; extensionIndex < path.Length; extensionIndex++ ) + { + char ch = path[extensionIndex]; + if( ch >= 65 && ch <= 90 ) // A-Z + ch += (char) 32; // Converted to a-z + + stringBuilder.Append( ch ); + } + + return stringBuilder.ToString(); + } + + // Draw horizontal line inside OnGUI + public static void DrawSeparatorLine() + { + GUILayout.Space( 4 ); + GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH ); + GUILayout.Space( 4 ); + } + // Check if all the objects inside the list are null public static bool IsEmpty( this List objectsToSearch ) { @@ -475,11 +506,33 @@ namespace AssetUsageDetectorNamespace return true; } - public static void DrawSeparatorLine() + // Returns true is str starts with prefix + public static bool StartsWithFast( this string str, string prefix ) { - GUILayout.Space( 4 ); - GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH ); - GUILayout.Space( 4 ); + int aLen = str.Length; + int bLen = prefix.Length; + int ap = 0; int bp = 0; + while( ap < aLen && bp < bLen && str[ap] == prefix[bp] ) + { + ap++; + bp++; + } + + return bp == bLen; + } + + // Returns true is str ends with postfix + public static bool EndsWithFast( this string str, string postfix ) + { + int ap = str.Length - 1; + int bp = postfix.Length - 1; + while( ap >= 0 && bp >= 0 && str[ap] == postfix[bp] ) + { + ap--; + bp--; + } + + return bp < 0; } public static bool ContainsFast( this List list, T element ) diff --git a/package.json b/package.json index 35d7005..f45a415 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "com.yasirkula.assetusagedetector", "displayName": "Asset Usage Detector", - "version": "1.8.0", + "version": "1.8.1", "description": "This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!" }