Compare commits

..

22 Commits

Author SHA1 Message Date
yasirkula b7b6f8815e Search results in scenes are simplified (i.e. 'Scene object A->Scene object B->Scene object C->Searched asset' references now become 'Scene object C->Searched asset') 2021-11-28 19:42:17 +03:00
yasirkula 40a28f5961 Fixed a bug where 'Scene object->Prefab->Asset' references would sometimes be skipped if Scene object wasn't referencing the correct component of the prefab 2021-11-28 19:35:37 +03:00
yasirkula b535e09ba2 Fixed a crucial bug that would cause some valid references to be skipped (e.g. Camera's 'Target Texture') 2021-11-28 19:32:16 +03:00
Süleyman Yasir KULA 499e4bc43e Added Discord link 2021-10-28 20:09:31 +03:00
yasirkula 93c955993a Previous commit applies to 'Refresh' buttons, as well 2021-10-21 15:08:46 +03:00
yasirkula 21f8daffde - Search can now be started even if some scene(s) aren't saved but the search results in those scene(s) may be incorrect
- lazySceneSearch and showDetailedProgressBar are enabled by default for better UX
2021-10-21 14:56:51 +03:00
yasirkula 8cc7798f17 Fixed a rare ArgumentNullException when searching an Animation/Animator component (#28) 2021-09-26 12:33:44 +03:00
yasirkula 45b0f6f1d9 Version 1.9.7 2021-07-25 18:00:33 +03:00
yasirkula c599ea6273 Duplicate asset usage descriptions in search results page are now omitted (i.e. "[Usage information][Usage information] Some asset" becomes "[Usage information] Some asset") 2021-07-25 17:49:30 +03:00
yasirkula 7ba33e2d4e When an asset in "Find references of:" list is right clicked, Refresh button appears which refreshes that asset's sub-assets list 2021-07-25 17:39:12 +03:00
yasirkula ac294324dd When a folder is assigned to a sprite atlas, all sprites in that folder are searched 2021-07-25 17:23:17 +03:00
yasirkula 8dc7d5508b ParticleSystem's Sub Emitters module is now searched correctly 2021-07-25 17:22:00 +03:00
Nika Burimenko c9131811e2 Sprites assigned to Particle System's Texture Sheet Animation Module are now detected (#26)
Fixed Sprite within Particle System's Texture Sheet Animation not being detected

Authored-by: Nika Burimenko <remedy89@gmail.com>
2021-07-25 16:37:44 +03:00
yasirkula 133b8b1227 Fixed small text issue on 2019.1 and 2019.2 (some devices might not have been affected by this issue) 2021-07-06 17:49:31 +03:00
yasirkula 1db9dbf9b0 Fixed issues with mysterious empty dependencies returned by AssetDatabase.GetDependencies 2021-06-09 12:35:25 +03:00
yasirkula a6b0f5ae92 Unity 2020 support 2021-05-18 13:47:38 +03:00
Süleyman Yasir KULA 8e7369e44e Some properties in Project Settings like "Quality Settings->SRP Asset" weren't included in search, fixed 2021-03-28 19:57:44 +03:00
Süleyman Yasir KULA 7b60eeacf7 If an exception occurs while searching for references via reflection, the problematic object will be skipped and a warning will be logged to the console instead of interrupting the whole search 2021-03-17 16:13:24 +03:00
Süleyman Yasir KULA b8470536b9 - Following variables of ParticleSystem are now included in search: LightsModule->Light, CollisionModule->Plane, TriggerModule->Collider
- Improved readability of texts in dark Editor skin
- Fixed "Animator is not playing an AnimatorController" warnings
- Fixed "TMP_Sprite Animator" component getting added to TextMesh Pro objects in the scene while searching for a scene object's references at runtime
2021-03-14 17:15:00 +03:00
Süleyman Yasir KULA 1bebc8691d Update package.json
Added documentationUrl, changelogUrl and licensesUrl to package.json
2021-01-19 12:51:21 +03:00
Süleyman Yasir KULA 5a81e5011b While using the Search for References button in right-click menu, if current scene setup is different from the initial scene setup, plugin now asks user whether or not they want to restore the initial scene setup instead of automatically restoring the initial scene setup 2020-12-22 22:46:22 +03:00
Süleyman Yasir KULA ba7539d983 References from Animator Override Controllers to their base Animator Controllers are now found 2020-11-18 13:46:42 +03:00
11 changed files with 391 additions and 175 deletions
+5 -3
View File
@@ -6,6 +6,8 @@
**Forum Thread:** https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/
**Discord:** https://discord.gg/UJJt549AaV
**[Support the Developer ☕](https://yasirkula.itch.io/unity3d)**
## ABOUT
@@ -41,6 +43,6 @@ There are 5 ways to install this plugin:
## KNOWN LIMITATIONS
- *static* variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched
- *static* variables aren't searched
- GUIText materials aren't searched
- Textures in Lens Flares can't be searched
@@ -43,13 +43,13 @@ namespace AssetUsageDetectorNamespace
public BindingFlags propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic;
public bool searchNonSerializableVariables = true;
public bool lazySceneSearch = false;
public bool lazySceneSearch = true;
public bool noAssetDatabaseChanges = false;
public bool showDetailedProgressBar = false;
public bool showDetailedProgressBar = true;
}
#endregion
// A set that contains the searched asset(s) and their sub-assets (if any)
// A set that contains the searched scene object(s), asset(s) and their sub-assets (if any)
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
// Scenes of scene object(s) in objectsToSearchSet
private readonly HashSet<string> sceneObjectsToSearchScenesSet = new HashSet<string>();
@@ -100,26 +100,16 @@ namespace AssetUsageDetectorNamespace
{
if( searchParameters == null )
{
Debug.LogError( "searchParameters must not be null!" );
Debug.LogError( "'searchParameters' mustn't be null!" );
return new SearchResult( false, null, null, this, searchParameters );
}
if( searchParameters.objectsToSearch == null )
{
Debug.LogError( "objectsToSearch list is empty!" );
Debug.LogError( "'objectsToSearch' list (\"Find references of:\") is empty!" );
return new SearchResult( false, null, null, this, searchParameters );
}
if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
{
// Don't start the search if at least one scene is currently dirty (not saved)
Debug.LogError( "Save open scenes first!" );
return new SearchResult( false, null, null, this, searchParameters );
}
List<SearchResultGroup> searchResult = null;
isInPlayMode = EditorApplication.isPlaying;
#if UNITY_2018_3_OR_NEWER
openPrefabStagePrefabAsset = null;
string openPrefabStageAssetPath = null;
@@ -133,7 +123,7 @@ namespace AssetUsageDetectorNamespace
if( openPrefabStage.scene.isDirty )
{
// Don't start the search if a prefab stage is currently open and dirty (not saved)
Debug.LogError( "Save open prefabs first!" );
Debug.LogError( "Save open prefab first!" );
return new SearchResult( false, null, null, this, searchParameters );
}
@@ -152,6 +142,15 @@ namespace AssetUsageDetectorNamespace
}
#endif
List<SearchResultGroup> searchResult = null;
isInPlayMode = EditorApplication.isPlaying;
if( !isInPlayMode && !Utilities.AreScenesSaved() && !EditorUtility.DisplayDialog( "Asset Usage Detector", "Some scene(s) aren't saved. This may result in incorrect search results in those scene(s). Proceed?", "Yes", "Cancel" ) )
{
Debug.LogError( "Save open scene(s) first!" );
return new SearchResult( false, null, null, this, searchParameters );
}
// Get the scenes that are open right now
SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null;
@@ -547,26 +546,10 @@ namespace AssetUsageDetectorNamespace
}
catch( Exception e )
{
StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 );
StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 1000 );
sb.AppendLine( "<b>AssetUsageDetector Error:</b>" ).AppendLine().Append( e ).AppendLine();
if( callStack.Count > 0 )
{
sb.AppendLine( "Stack contents: " );
for( int i = callStack.Count - 1; i >= 0; i-- )
{
sb.Append( i ).Append( ": " );
Object unityObject = callStack[i] as Object;
if( unityObject )
sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" );
else if( callStack[i] != null )
sb.Append( callStack[i].GetType() ).AppendLine( " object" );
else
sb.AppendLine( "<<destroyed>>" );
}
sb.AppendLine();
}
Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb );
sb.AppendLine( "Searching references of: " );
foreach( Object obj in objectsToSearchSet )
@@ -575,7 +558,7 @@ namespace AssetUsageDetectorNamespace
sb.Append( obj.name ).Append( " (" ).Append( obj.GetType() ).AppendLine( ")" );
}
Debug.LogError( sb.ToString() );
Debug.LogError( sb.ToString(), latestUnityObjectInCallStack );
try
{
@@ -616,7 +599,9 @@ namespace AssetUsageDetectorNamespace
if( shouldOpenPrefabStageWithoutContext )
#endif
AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) );
{
AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) );
}
}
#endif
}
@@ -625,7 +610,7 @@ namespace AssetUsageDetectorNamespace
private void InitializeSearchResultNodes( List<SearchResultGroup> searchResult )
{
for( int i = 0; i < searchResult.Count; i++ )
searchResult[i].InitializeNodes( GetReferenceNode );
searchResult[i].InitializeNodes( GetReferenceNode, objectsToSearchSet );
// If there are any empty groups after node initialization, remove those groups
for( int i = searchResult.Count - 1; i >= 0; i-- )
@@ -1087,5 +1072,48 @@ namespace AssetUsageDetectorNamespace
Object.DestroyImmediate( temp );
}
}
// Appends contents of callStack to StringBuilder and returns the most recent Unity object in callStack
private Object AppendCallStackToStringBuilder( StringBuilder sb )
{
Object latestUnityObjectInCallStack = null;
if( callStack.Count > 0 )
{
sb.AppendLine().AppendLine( "Stack contents: " );
for( int i = callStack.Count - 1; i >= 0; i-- )
{
latestUnityObjectInCallStack = callStack[i] as Object;
if( latestUnityObjectInCallStack )
{
if( !AssetDatabase.Contains( latestUnityObjectInCallStack ) )
{
string scenePath = AssetDatabase.GetAssetOrScenePath( latestUnityObjectInCallStack );
if( !string.IsNullOrEmpty( scenePath ) && SceneManager.GetSceneByPath( scenePath ).IsValid() )
sb.Append( "Scene: " ).AppendLine( scenePath );
}
break;
}
}
for( int i = callStack.Count - 1; i >= 0; i-- )
{
sb.Append( i ).Append( ": " );
Object unityObject = callStack[i] as Object;
if( unityObject )
sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" );
else if( callStack[i] != null )
sb.Append( callStack[i].GetType() ).AppendLine( " object" );
else
sb.AppendLine( "<<destroyed>>" );
}
sb.AppendLine();
}
return latestUnityObjectInCallStack;
}
}
}
@@ -51,10 +51,35 @@ namespace AssetUsageDetectorNamespace
if( fileSizes == null || fileSizes.Length != dependencies.Length )
fileSizes = new long[dependencies.Length];
for( int i = 0; i < dependencies.Length; i++ )
int length = dependencies.Length;
for( int i = 0; i < length; i++ )
{
FileInfo assetFile = new FileInfo( dependencies[i] );
fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L;
if( !string.IsNullOrEmpty( dependencies[i] ) )
{
FileInfo assetFile = new FileInfo( dependencies[i] );
fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L;
}
else
{
// This dependency is empty which causes issues when passed to FileInfo constructor
// Find a non-empty dependency and move it to this index
for( int j = length - 1; j > i; j--, length-- )
{
if( !string.IsNullOrEmpty( dependencies[j] ) )
{
dependencies[i--] = dependencies[j];
break;
}
}
length--;
}
}
if( length != fileSizes.Length )
{
Array.Resize( ref dependencies, length );
Array.Resize( ref fileSizes, length );
}
}
}
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;
@@ -382,14 +383,6 @@ namespace AssetUsageDetectorNamespace
if( objectsToSearchSet.Contains( script ) )
referenceNode.AddLinkTo( GetReferenceNode( script ) );
}
else if( component is ParticleSystemRenderer )
{
// Search ParticleSystemRenderer's custom meshes for references (they aren't searched by SerializedObject, unfortunately)
Mesh[] meshes = new Mesh[( (ParticleSystemRenderer) component ).meshCount];
int meshCount = ( (ParticleSystemRenderer) component ).GetMeshes( meshes );
for( int i = 0; i < meshCount; i++ )
referenceNode.AddLinkTo( SearchObject( meshes[i] ), "Custom particle mesh" );
}
else if( searchRenderers && component is Renderer )
{
// If an asset is a shader, texture or material, and this component is a Renderer,
@@ -569,6 +562,13 @@ namespace AssetUsageDetectorNamespace
}
else
{
if( controller is AnimatorOverrideController )
{
RuntimeAnimatorController parentController = ( (AnimatorOverrideController) controller ).runtimeAnimatorController;
if( objectsToSearchSet.Contains( parentController ) )
referenceNode.AddLinkTo( GetReferenceNode( parentController ) );
}
AnimationClip[] animClips = controller.animationClips;
for( int i = 0; i < animClips.Length; i++ )
referenceNode.AddLinkTo( SearchObject( animClips[i] ) );
@@ -685,19 +685,61 @@ namespace AssetUsageDetectorNamespace
if( packables != null )
{
for( int i = 0; i < packables.Length; i++ )
referenceNode.AddLinkTo( SearchObject( packables[i] ), "Packed Texture" );
SearchSpriteAtlas( referenceNode, packables[i] );
}
#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" );
SearchSpriteAtlas( referenceNode, packables.GetArrayElementAtIndex( i ).objectReferenceValue );
}
#endif
return referenceNode;
}
private void SearchSpriteAtlas( ReferenceNode referenceNode, Object packedAsset )
{
if( packedAsset == null || packedAsset.Equals( null ) )
return;
referenceNode.AddLinkTo( SearchObject( packedAsset ), "Packed Texture" );
if( packedAsset is Texture )
{
// Search the Texture's sprites if the Texture asset isn't included in the "Find references of:" list (i.e. user has
// added only a Sprite sub-asset of the Texture to the list, not the Texture asset itself). Otherwise, references to
// both the Texture and its sprites will be found which can be considered as duplicate references
if( AssetDatabase.IsMainAsset( packedAsset ) && !assetsToSearchSet.Contains( packedAsset ) )
{
Object[] textureSubAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( packedAsset ) );
for( int i = 0; i < textureSubAssets.Length; i++ )
{
if( textureSubAssets[i] is Sprite )
referenceNode.AddLinkTo( SearchObject( textureSubAssets[i] ), "Packed Texture" );
}
}
}
else if( packedAsset.IsFolder() )
{
// Search all Sprites in the folder
string[] texturesInFolder = AssetDatabase.FindAssets( "t:Texture2D", new string[] { AssetDatabase.GetAssetPath( packedAsset ) } );
if( texturesInFolder != null )
{
for( int i = 0; i < texturesInFolder.Length; i++ )
{
string texturePath = AssetDatabase.GUIDToAssetPath( texturesInFolder[i] );
TextureImporter textureImporter = AssetImporter.GetAtPath( texturePath ) as TextureImporter;
if( textureImporter != null && textureImporter.textureType == TextureImporterType.Sprite )
{
// Search the Texture and its sprites
SearchSpriteAtlas( referenceNode, AssetDatabase.LoadMainAssetAtPath( texturePath ) );
}
}
}
}
}
#endif
#if UNITY_2017_3_OR_NEWER
@@ -879,6 +921,9 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < clips.Length; i++ )
{
AnimationClip clip = clips[i];
if( !clip )
continue;
bool isClipUnique = true;
for( int j = i - 1; j >= 0; j-- )
{
@@ -1000,7 +1045,7 @@ namespace AssetUsageDetectorNamespace
// those properties aren't interesting and mostly confusing)
bool isVisible = iteratingVisible && SerializedProperty.EqualContents( iterator, iteratorVisible );
if( isVisible )
iteratingVisible = iteratorVisible.NextVisible( true );
iteratingVisible = iteratorVisible.NextVisible( iteratorVisible.propertyType == SerializedPropertyType.Generic );
else
{
Type propFieldType;
@@ -1017,16 +1062,16 @@ namespace AssetUsageDetectorNamespace
switch( iterator.propertyType )
{
case SerializedPropertyType.ObjectReference:
searchResult = SearchObject( iterator.objectReferenceValue );
searchResult = SearchObject( PreferablyGameObject( iterator.objectReferenceValue ) );
enterChildren = false;
break;
case SerializedPropertyType.ExposedReference:
searchResult = SearchObject( iterator.exposedReferenceValue );
searchResult = SearchObject( PreferablyGameObject( iterator.exposedReferenceValue ) );
enterChildren = false;
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference:
searchResult = SearchObject( GetRawSerializedPropertyValue( iterator ) );
searchResult = SearchObject( PreferablyGameObject( GetRawSerializedPropertyValue( iterator ) ) );
enterChildren = false;
break;
#endif
@@ -1072,14 +1117,14 @@ namespace AssetUsageDetectorNamespace
try
{
object variableValue = variables[i].Get( referenceNode.nodeObject );
if( variableValue == null )
if( variableValue == null || variableValue.Equals( 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 );
ReferenceNode searchResult = SearchObject( PreferablyGameObject( variableValue ) );
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
}
@@ -1091,7 +1136,7 @@ namespace AssetUsageDetectorNamespace
int index = 0;
foreach( object element in (IEnumerable) variableValue )
{
ReferenceNode searchResult = SearchObject( element );
ReferenceNode searchResult = SearchObject( PreferablyGameObject( element ) );
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) );
@@ -1103,6 +1148,15 @@ namespace AssetUsageDetectorNamespace
catch( MissingReferenceException ) { }
catch( MissingComponentException ) { }
catch( NotImplementedException ) { }
catch( Exception e )
{
// Unknown exceptions usually occur when variableValue is an IEnumerable and its enumerator throws an unhandled exception in MoveNext or Current
StringBuilder sb = new StringBuilder( callStack.Count * 50 + 1000 );
sb.Append( "Skipped searching " ).Append( referenceNode.nodeObject.GetType().FullName ).Append( "." ).Append( variables[i].name ).AppendLine( " because it threw exception:" ).Append( e ).AppendLine();
Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb );
Debug.LogWarning( sb.ToString(), latestUnityObjectInCallStack );
}
}
}
@@ -1189,22 +1243,20 @@ namespace AssetUsageDetectorNamespace
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;
// Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of components to get more useful results
if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" ||
propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) )
continue;
// Ignore "canvasRenderer" and "canvas" properties of Graphic components to get more useful results
else if( typeof( Graphic ).IsAssignableFrom( currType ) &&
( propertyName == "canvasRenderer" || propertyName == "canvas" ) )
continue;
// Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak)
else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" )
continue;
else if( typeof( Renderer ).IsAssignableFrom( currType ) &&
( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) )
continue;
// Same as above
else if( ( propertyName == "material" || propertyName == "materials" ) &&
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) ||
#if !UNITY_2019_3_OR_NEWER
@@ -1214,6 +1266,19 @@ namespace AssetUsageDetectorNamespace
#endif
typeof( Collider2D ).IsAssignableFrom( currType ) ) )
continue;
// "sharedMaterials" are searched via SearchComponent, no need to search it with reflection, as well
else if( typeof( Renderer ).IsAssignableFrom( currType ) &&
( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) )
continue;
// Ignore "parameters" property of Animator since it doesn't contain any useful data and logs a warning to the console when Animator is inactive
else if( typeof( Animator ).IsAssignableFrom( currType ) && propertyName == "parameters" )
continue;
// Ignore "spriteAnimator" property of TMP_Text component because this property adds a TMP_SpriteAnimator component to the object if it doesn't exist
else if( propertyName == "spriteAnimator" && currType.Name == "TMP_Text" )
continue;
// Ignore "meshFilter" property of TextMeshPro and TMP_SubMesh components because this property adds a MeshFilter component to the object if it doesn't exist
else if( propertyName == "meshFilter" && ( currType.Name == "TextMeshPro" || currType.Name == "TMP_SubMesh" ) )
continue;
else
{
VariableGetVal getter = property.CreateGetter();
@@ -1336,5 +1401,12 @@ namespace AssetUsageDetectorNamespace
valueAction( str.Substring( valueStartIndex, valueEndIndex - valueStartIndex ) );
}
}
// If obj is Component, switches to its GameObject
private object PreferablyGameObject( object obj )
{
Component component = obj as Component;
return ( component != null && !component.Equals( null ) ) ? component.gameObject : obj;
}
}
}
@@ -55,14 +55,10 @@ namespace AssetUsageDetectorNamespace
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool restoreInitialSceneSetup = true; // Close the additively loaded scenes that were not part of the initial scene setup
private string errorMessage = string.Empty;
private bool lazySceneSearch = false;
private bool lazySceneSearch = true;
private bool searchNonSerializableVariables = true;
private bool noAssetDatabaseChanges = false;
private bool showDetailedProgressBar = false;
private bool showDetailedProgressBar = true;
private BindingFlags fieldModifiers, propertyModifiers;
@@ -75,7 +71,6 @@ 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;
@@ -193,7 +188,7 @@ namespace AssetUsageDetectorNamespace
private static void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren )
{
if( mainWindow != null && !mainWindow.ReturnToSetupPhase( true ) )
if( mainWindow && !mainWindow.ReturnToSetupPhase() )
{
Debug.LogError( "Need to reset the previous search first!" );
return;
@@ -280,11 +275,8 @@ namespace AssetUsageDetectorNamespace
SavePrefs();
if( searchResult != null && currentPhase == Phase.Complete && !EditorApplication.isPlaying && searchResult.IsSceneSetupDifferentThanCurrentSetup() )
{
if( EditorUtility.DisplayDialog( "Scenes", "Restore initial scene setup?", "Yes", "Leave it as is" ) )
searchResult.RestoreInitialSceneSetup();
}
if( searchResult != null && currentPhase == Phase.Complete )
searchResult.RestoreInitialSceneSetup();
}
private void OnFocus()
@@ -331,9 +323,9 @@ namespace AssetUsageDetectorNamespace
}
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, false );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
searchResultDrawParameters.showTooltips = EditorPrefs.GetBool( PREFS_SHOW_TOOLTIPS, false );
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, false );
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
}
private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
@@ -383,37 +375,24 @@ namespace AssetUsageDetectorNamespace
GUILayout.BeginVertical();
GUILayout.Space( 10 );
// Show the error message, if it is not empty
if( errorMessage.Length > 0 )
EditorGUILayout.HelpBox( errorMessage, MessageType.Error );
GUILayout.Space( 10 );
if( currentPhase == Phase.Processing )
{
// If we are stuck at this phase, then we have encountered an exception
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
ReturnToSetupPhase();
}
else if( currentPhase == Phase.Setup )
{
if( objectsToSearchDrawer.Draw( objectsToSearch ) )
errorMessage = string.Empty;
objectsToSearchDrawer.Draw( objectsToSearch );
GUILayout.Space( 10 );
Color c = GUI.color;
GUI.color = Color.cyan;
Color c = GUI.backgroundColor;
GUI.backgroundColor = Color.cyan;
GUILayout.Box( "SEARCH IN", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
GUI.backgroundColor = c;
searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
@@ -526,15 +505,13 @@ namespace AssetUsageDetectorNamespace
//GUILayout.Space( 10 );
GUI.color = Color.cyan;
GUI.backgroundColor = Color.cyan;
GUILayout.Box( "SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
GUI.backgroundColor = c;
lazySceneSearch = EditorGUILayout.ToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
showDetailedProgressBar = EditorGUILayout.ToggleLeft( "Show detailed progress bar (slower search)", showDetailedProgressBar );
showDetailedProgressBar = EditorGUILayout.ToggleLeft( "Update search progress bar more often (slower search)", showDetailedProgressBar );
GUILayout.Space( 10 );
@@ -558,10 +535,8 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10 );
GUI.enabled = true;
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
ReturnToSetupPhase();
if( searchResult == null )
{
@@ -571,10 +546,10 @@ namespace AssetUsageDetectorNamespace
else if( !searchResult.SearchCompletedSuccessfully )
EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error );
Color c = GUI.color;
GUI.color = Color.green;
Color c = GUI.backgroundColor;
GUI.backgroundColor = Color.green;
GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
GUI.backgroundColor = c;
if( searchResult.NumberOfGroups == 0 )
{
@@ -654,46 +629,35 @@ namespace AssetUsageDetectorNamespace
private void InitiateSearch()
{
if( objectsToSearch.IsEmpty() )
errorMessage = "ADD AN ASSET TO THE LIST FIRST!";
else if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
{
// Don't start the search if at least one scene is currently dirty (not saved)
errorMessage = "SAVE OPEN SCENES FIRST!";
}
else
{
errorMessage = string.Empty;
currentPhase = Phase.Processing;
currentPhase = Phase.Processing;
SavePrefs();
SavePrefs();
#if UNITY_2018_3_OR_NEWER
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
#endif
// Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = new ObjectToSearchEnumerator( objectsToSearch ).ToArray(),
searchInScenes = GetSceneSearchMode( true ),
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
searchInProjectSettings = searchInProjectSettings,
//fieldModifiers = fieldModifiers,
//propertyModifiers = propertyModifiers,
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
lazySceneSearch = lazySceneSearch,
noAssetDatabaseChanges = noAssetDatabaseChanges,
showDetailedProgressBar = showDetailedProgressBar
} );
// Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
searchInScenes = GetSceneSearchMode( true ),
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
searchInProjectSettings = searchInProjectSettings,
//fieldModifiers = fieldModifiers,
//propertyModifiers = propertyModifiers,
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
lazySceneSearch = lazySceneSearch,
noAssetDatabaseChanges = noAssetDatabaseChanges,
showDetailedProgressBar = showDetailedProgressBar
} );
currentPhase = Phase.Complete;
}
currentPhase = Phase.Complete;
}
#if UNITY_2018_3_OR_NEWER
@@ -736,14 +700,12 @@ namespace AssetUsageDetectorNamespace
}
#endif
private bool ReturnToSetupPhase( bool restoreInitialSceneSetup )
private bool ReturnToSetupPhase()
{
if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
if( searchResult != null && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
return false;
searchResult = null;
errorMessage = string.Empty;
currentPhase = Phase.Setup;
return true;
@@ -86,12 +86,18 @@ namespace AssetUsageDetectorNamespace
Object prevObject = GetObjectFromElement( element );
Object newObject = EditorGUILayout.ObjectField( "", prevObject, typeof( Object ), acceptSceneObjects );
if( GUI.changed && prevObject != newObject )
if( GUI.changed )
{
hasChanged = true;
SetObjectOfElement( list, i, newObject );
}
if( guiEnabled && newObject && ev.type == EventType.ContextClick && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
OnElementRightClicked( list, i, newObject );
ev.Use();
}
if( guiEnabled )
{
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
@@ -121,6 +127,7 @@ namespace AssetUsageDetectorNamespace
protected abstract T CreateElement( Object source );
protected abstract Object GetObjectFromElement( T element );
protected abstract void SetObjectOfElement( List<T> list, int index, Object value );
protected abstract void OnElementRightClicked( List<T> list, int index, Object value );
protected abstract bool IsElementNull( T element );
protected abstract void PostElementDrawer( T element );
}
@@ -146,6 +153,10 @@ namespace AssetUsageDetectorNamespace
list[index] = value;
}
protected override void OnElementRightClicked( List<Object> list, int index, Object value )
{
}
protected override bool IsElementNull( Object element )
{
return element == null || element.Equals( null );
@@ -178,6 +189,13 @@ namespace AssetUsageDetectorNamespace
list[index].RefreshSubAssets();
}
protected override void OnElementRightClicked( List<ObjectToSearch> list, int index, Object value )
{
GenericMenu contextMenu = new GenericMenu();
contextMenu.AddItem( new GUIContent( "Refresh" ), false, () => SetObjectOfElement( list, index, value ) );
contextMenu.ShowAsContext();
}
protected override bool IsElementNull( ObjectToSearch element )
{
return element == null || element.obj == null || element.obj.Equals( null );
+100 -13
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
@@ -333,7 +334,24 @@ namespace AssetUsageDetectorNamespace
if( initialSceneSetup == null || initialSceneSetup.Length == 0 )
return true;
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
if( EditorApplication.isPlaying )
return false;
if( !IsSceneSetupDifferentThanCurrentSetup() )
return true;
StringBuilder sb = new StringBuilder( 300 );
sb.AppendLine( "Restore initial scene setup?" );
for( int i = 0; i < initialSceneSetup.Length; i++ )
sb.AppendLine().Append( "- " ).Append( initialSceneSetup[i].path );
switch( EditorUtility.DisplayDialogComplex( "Asset Usage Detector", sb.ToString(), "Yes", "Cancel", "Leave it as is" ) )
{
case 1: return false;
case 2: return true;
}
if( !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
return false;
for( int i = 0; i < initialSceneSetup.Length; i++ )
@@ -497,7 +515,7 @@ namespace AssetUsageDetectorNamespace
}
// Initializes commonly used variables of the nodes
public void InitializeNodes( Func<object, ReferenceNode> nodeGetter )
public void InitializeNodes( Func<object, ReferenceNode> nodeGetter, HashSet<Object> objectsToSearchSet )
{
// Remove root nodes that don't have any outgoing links or have null node objects (somehow)
for( int i = references.Count - 1; i >= 0; i-- )
@@ -526,6 +544,26 @@ namespace AssetUsageDetectorNamespace
List<ReferenceNode> callStack = new List<ReferenceNode>( 8 );
// If this SearchResultGroup belongs to a scene, simplify the root nodes so that they go directly to either the searched objects or to an asset in a single link
if( Type == GroupType.Scene || Type == GroupType.DontDestroyOnLoad )
{
Scene scene = references[0].nodeObject is GameObject ? ( (GameObject) references[0].nodeObject ).scene : ( (Component) references[0].nodeObject ).gameObject.scene;
HashSet<ReferenceNode> leafNodes = new HashSet<ReferenceNode>();
for( int i = references.Count - 1; i >= 0; i-- )
{
references[i].GetLeafSceneNodesRecursive( scene, leafNodes, references[i], objectsToSearchSet, callStack );
if( leafNodes.Count > 0 )
{
references.RemoveAt( i );
foreach( ReferenceNode leafNode in leafNodes )
references.Add( leafNode );
leafNodes.Clear();
}
}
}
// For simplicity's sake, get rid of root nodes that are already part of another node's hierarchy
for( int i = references.Count - 1; i >= 0; i-- )
{
@@ -679,8 +717,8 @@ namespace AssetUsageDetectorNamespace
parameters.shouldRefreshEditorWindow = true; // A repaint is needed to work nicely with GUILayout
}
Color c = GUI.color;
GUI.color = Color.cyan;
Color c = GUI.backgroundColor;
GUI.backgroundColor = Color.cyan;
Rect rect = parameters.guiRect;
float width = rect.width;
@@ -726,11 +764,8 @@ namespace AssetUsageDetectorNamespace
rect.width = 100f;
if( GUI.Button( rect, "Refresh" ) )
{
if( Utilities.AreScenesSaved() || ( EditorUtility.DisplayDialog( "Refresh", "Some scene(s) have unsaved changes, they must be saved before the refresh.", "Save Scenes", "Cancel" ) && EditorSceneManager.SaveOpenScenes() ) )
{
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
}
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
}
}
@@ -739,7 +774,8 @@ namespace AssetUsageDetectorNamespace
if( IsExpanded )
{
GUI.color = Color.yellow;
// On light skin, yellow background looks better than light grey background
GUI.backgroundColor = EditorGUIUtility.isProSkin ? c : Color.yellow;
if( PendingSearch )
{
@@ -764,7 +800,7 @@ namespace AssetUsageDetectorNamespace
}
parameters.guiRect = rect;
GUI.color = c;
GUI.backgroundColor = c;
}
private void GenerateGUINodes( SearchResultDrawParameters parameters )
@@ -920,7 +956,11 @@ namespace AssetUsageDetectorNamespace
if( !string.IsNullOrEmpty( description ) )
{
if( !string.IsNullOrEmpty( links[i].description ) )
links[i] = new Link( links[i].targetNode, string.Concat( links[i].description, Environment.NewLine, description ) );
{
// Avoid duplicate descriptions
if( !links[i].description.Contains( description ) )
links[i] = new Link( links[i].targetNode, string.Concat( links[i].description, Environment.NewLine, description ) );
}
else
links[i] = new Link( links[i].targetNode, description );
}
@@ -990,12 +1030,59 @@ namespace AssetUsageDetectorNamespace
description = "<<destroyed>>";
}
nodeObject = null; // don't hold Object reference, allow Unity to GC used memory
nodeObject = null; // Don't hold Object reference, allow Unity to GC used memory
for( int i = 0; i < links.Count; i++ )
links[i].targetNode.InitializeRecursively();
}
// Finds all leaf nodes that originate from this node and have GameObject/Component node objects in the specified scene
public void GetLeafSceneNodesRecursive( Scene scene, HashSet<ReferenceNode> leafNodes, ReferenceNode latestSceneObjectNode, HashSet<Object> objectsToSearchSet, List<ReferenceNode> callStack )
{
if( links.Count == 0 || callStack.ContainsFast( this ) || ( nodeObject is Object && objectsToSearchSet.Contains( (Object) nodeObject ) ) ) // This is a searched object's node
{
leafNodes.Add( latestSceneObjectNode );
return;
}
Object unityObject = nodeObject as Object;
if( unityObject != null )
{
if( AssetDatabase.Contains( unityObject ) )
{
leafNodes.Add( latestSceneObjectNode );
return;
}
else if( unityObject is Component )
{
if( ( (Component) unityObject ).gameObject.scene == scene )
latestSceneObjectNode = this;
else
{
leafNodes.Add( latestSceneObjectNode );
return;
}
}
else if( unityObject is GameObject )
{
if( ( (GameObject) unityObject ).scene == scene )
latestSceneObjectNode = this;
else
{
leafNodes.Add( latestSceneObjectNode );
return;
}
}
}
callStack.Add( this );
for( int i = 0; i < links.Count; i++ )
links[i].targetNode.GetLeafSceneNodesRecursive( scene, leafNodes, latestSceneObjectNode, objectsToSearchSet, callStack );
callStack.RemoveAt( callStack.Count - 1 );
}
// Returns whether or not specified node is part of this node's siblings
public bool NodeExistsInChildrenRecursive( ReferenceNode node, List<ReferenceNode> callStack )
{
+26 -1
View File
@@ -81,6 +81,18 @@ namespace AssetUsageDetectorNamespace
alignment = TextAnchor.MiddleCenter,
font = EditorStyles.label.font
};
Color textColor = GUI.skin.button.normal.textColor;
m_boxGUIStyle.normal.textColor = textColor;
m_boxGUIStyle.hover.textColor = textColor;
m_boxGUIStyle.focused.textColor = textColor;
m_boxGUIStyle.active.textColor = textColor;
#if !UNITY_2019_1_OR_NEWER || UNITY_2019_3_OR_NEWER
// On 2019.1 and 2019.2 versions, GUI.skin.button.fontSize returns 0 on some devices
// https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/page-3#post-7285954
m_boxGUIStyle.fontSize = ( m_boxGUIStyle.fontSize + GUI.skin.button.fontSize ) / 2;
#endif
}
return m_boxGUIStyle;
@@ -446,7 +458,20 @@ namespace AssetUsageDetectorNamespace
{
// Can't use PropertyWrapper (which uses CreateDelegate) for property getters of structs
if( propertyInfo.DeclaringType.IsValueType )
return propertyInfo.CanRead ? ( ( obj ) => propertyInfo.GetValue( obj, null ) ) : (VariableGetVal) null;
{
return !propertyInfo.CanRead ? (VariableGetVal) null : ( obj ) =>
{
try
{
return propertyInfo.GetValue( obj, null );
}
catch
{
// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
return null;
}
};
}
Type GenType = typeof( PropertyWrapper<,> ).MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType );
return ( (IPropertyAccessor) Activator.CreateInstance( GenType, propertyInfo.GetGetMethod( true ) ) ).GetValue;
@@ -69,8 +69,7 @@ namespace AssetUsageDetectorNamespace
}
catch
{
// Property getters may return various kinds of exceptions
// if their backing fields are not initialized (yet)
// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
return null;
}
}
+3 -8
View File
@@ -3,17 +3,12 @@
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
1. ABOUT
### ABOUT
This tool helps you find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. lists the objects that refer to them.
2. HOW TO
### HOW TO
Open "Window-Asset Usage Detector" window, configure the settings and hit GO! You can also right click an object and select "Search For References".
In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the
references are formed. If a node's label contains text inside square brackets (e.g. [Child object]), then that text describes how that node is
connected to the node to its left.
3. KNOWN LIMITATIONS
- static variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched
connected to the node to its left.
+4 -1
View File
@@ -1,6 +1,9 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "1.8.8",
"version": "2.0.0",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",
"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!"
}