Compare commits

..

40 Commits

Author SHA1 Message Date
yasirkula 962f6e04d4 Changed "Hide non-overridden prefab variables" options to "Hide redundant prefab references" which now also apply to C# scripts' and prefab assets' usages (#42) 2024-12-10 19:58:09 +03:00
yasirkula 204de979ba SearchResultGroup's "Hide Search Results" context menu button automatically exits the search 2024-12-10 19:13:58 +03:00
yasirkula 50ce6f56c9 Tiny fix for a switch-case that couldn't be properly auto indentated 2024-12-10 19:05:58 +03:00
yasirkula 0f872ef04d Fix for a tiny warning 2024-12-10 19:04:28 +03:00
yasirkula f68c8a1375 Added AssetUsageDetectorWindow.BeginIndentedGUI and EndIndentedGUI functions to reduce duplicate OnGUI code 2024-12-10 19:04:04 +03:00
yasirkula ecfb1adf88 Added Utilities.DrawHeader function to reduce duplicate OnGUI code 2024-12-10 19:01:23 +03:00
yasirkula e63ebd7f85 Simplifications in Utilities.IsEmpty 2024-12-10 18:59:28 +03:00
yasirkula d5b082c093 Added "Hide Search Results" to search result groups' context menu if their search results are filtered via a search term (i.e. text filtering). For example, you can filter search results with term "[Prefab object]" and then right click the group and select this option to hide all prefab instance occurrences in that group 2024-11-03 12:52:18 +03:00
yasirkula 1faa789f48 Removed an unused variable 2024-11-02 14:56:30 +03:00
yasirkula 610fffc763 Added "Hide non-overridden prefab variables in scenes" setting (closed #42) + Renamed "Hide redundant prefab variant links" to "Hide non-overridden prefab variables in assets" 2024-11-02 14:55:40 +03:00
yasirkula 9fddcab6fa Added 'Hide unused sub-assets in "Unused Objects" list if their parent assets are used' option to Settings (closed #39) 2024-08-04 13:24:44 +03:00
yasirkula 66dd66787c Fixed NullReferenceException on newest Unity versions if VFX Graph package is installed 2024-05-12 13:02:28 +03:00
yasirkula da921c2e06 "Hide redundant prefab variant links" setting now works as expected, only affecting variables in components and not affecting prefab/MonoScript usages 2023-11-18 17:53:42 +03:00
yasirkula d9cc52cc37 Fixed some properties not being searched in edge cases that may occur when Addressables or VFX Graph packages are present in the project 2023-11-18 17:50:27 +03:00
yasirkula e6641bef48 "Show Root Asset's Name" setting is enabled by default + root asset's name is prepended by "in" word for more clarity 2023-11-18 17:46:28 +03:00
yasirkula a6d91a58a3 Scenes in read-only packages aren't searched since they can't be opened (fixed #36) (closed #37) 2023-11-18 17:45:22 +03:00
yasirkula ace8ac4947 Bumped version 2023-10-07 20:43:03 +03:00
yasirkula 02167c28a2 "Show Children In New Window" window no longer auto-closes when clicked outside 2023-10-07 20:42:53 +03:00
yasirkula 092b80ba29 Fixed some references initially being displayed collapsed after the search 2023-10-07 20:41:10 +03:00
yasirkula 524965aee7 If an exception is thrown while accessing a variable via reflection, a more detailed error message is logged 2023-10-07 20:40:21 +03:00
yasirkula efad9fa158 Muted an exception that is raised while searching "ref struct"s for reference 2023-10-07 20:39:31 +03:00
yasirkula 6cd2b407cc Scene lighting settings are now searched for references (can be turned off) 2023-10-07 20:38:37 +03:00
yasirkula 3c4292159a Fixed deprecated EditorSceneManager warnings on 2022.2+ 2023-08-31 07:10:51 +03:00
yasirkula 1a2eba24bd Added a setting to show sub-assets' root asset names in search results (disabled by default) (closes #35) 2023-06-27 14:02:34 +03:00
yasirkula cf0fea56ab Fixed 3D model assets' direct children not being pinged correctly when selected via a search result 2023-06-27 14:01:20 +03:00
yasirkula 956aea1ced Added GitHub Sponsors link to README 2023-05-31 11:21:14 +03:00
Süleyman Yasir KULA 466a152ba6 Update README.md 2023-05-07 21:49:19 +03:00
yasirkula 5eda0c1cb0 Added VFX Graph support 2023-05-07 21:47:22 +03:00
yasirkula 42e3278129 Fixed not being able to ping some asset search results in Project window (in particular, VFX graph search results) 2023-05-07 21:38:28 +03:00
yasirkula f6a999f053 Fixed an exception that occurs when a VFX Graph window is open and the open VFX Graph asset is searched for references (there may be other similar edge cases, as well) 2023-05-07 21:37:38 +03:00
yasirkula 8441e4701c Addressables support no longer requires manual modifications 2023-05-07 21:36:05 +03:00
yasirkula d57a707678 Fixed exceptions while searching for some URP assets' references due to their overriden GetHashCode functions 2023-03-18 15:12:13 +03:00
yasirkula 3fa3344507 Fixed #33 2023-03-18 15:09:37 +03:00
yasirkula 8072530c2c Added experimental Addressables support (requires manual modifications) (closed #29) 2022-10-15 17:11:42 +03:00
yasirkula 28a73e2843 Shaders are searched for #include_with_pragmas references in addition to #include references 2022-09-23 14:17:52 +03:00
yasirkula c7e52466ef Added Collapse All button to Asset Usage Detector window's context menu that collapses all search result groups at once 2022-09-23 14:16:52 +03:00
yasirkula 875f3e6794 Fixed right clicking Unused Objects group throwing an exception if that search result group hasn't been expanded yet 2022-09-23 14:16:04 +03:00
yasirkula 635d0653fa Material's color and mainTexture properties aren't searched at runtime since they're searched by SearchMaterial anyways and they can actually throw errors in the Console if the corresponding shader property doesn't exist 2022-09-23 14:15:13 +03:00
yasirkula cb4454b493 - Terrains are now searched properly
- Fixed an error on latest Unity versions when clicking the "Reset Search" button
2022-07-23 21:53:11 +03:00
yasirkula dfb8541605 Fixed compiler errors on 2021.2 and later 2022-04-24 15:14:47 +03:00
12 changed files with 816 additions and 362 deletions
+2 -2
View File
@@ -8,7 +8,7 @@
**Discord:** https://discord.gg/UJJt549AaV
**[Support the Developer ☕](https://yasirkula.itch.io/unity3d)**
**[GitHub Sponsors ☕](https://github.com/sponsors/yasirkula)**
## ABOUT
@@ -66,8 +66,8 @@ void ReplaceFontUsages( Font from, Font to )
## KNOWN LIMITATIONS
- *Addressables* aren't supported
- *static* variables aren't searched
- *Resources.Load* usages can't be found
- *ref struct*s can't be searched
- *GUIText* materials aren't searched
- Textures in *Lens Flares* can't be searched
@@ -1,6 +1,9 @@
{
"name": "AssetUsageDetector.Editor",
"references": [],
"rootNamespace": "",
"references": [
"Unity.Addressables"
],
"includePlatforms": [
"Editor"
],
@@ -10,6 +13,17 @@
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"versionDefines": [
{
"name": "com.unity.addressables",
"expression": "0.0.0",
"define": "ASSET_USAGE_ADDRESSABLES"
},
{
"name": "com.unity.visualeffectgraph",
"expression": "0.0.0",
"define": "ASSET_USAGE_VFX_GRAPH"
}
],
"noEngineReferences": false
}
@@ -10,7 +10,7 @@ using System;
using System.IO;
using System.Text;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -31,6 +31,7 @@ namespace AssetUsageDetectorNamespace
public SceneSearchMode searchInScenes = SceneSearchMode.AllScenes;
public Object[] searchInScenesSubset = null;
public Object[] excludedScenesFromSearch = null;
public bool searchInSceneLightingSettings = true;
public bool searchInAssetsFolder = true;
public Object[] searchInAssetsSubset = null;
public Object[] excludedAssetsFromSearch = null;
@@ -47,9 +48,13 @@ namespace AssetUsageDetectorNamespace
public SearchRefactoring searchRefactoring = null;
public bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
public bool addressablesSupport = false;
#endif
public bool calculateUnusedObjects = false;
public bool hideDuplicateRows = true;
public bool hideReduntantPrefabVariantLinks = true;
public bool hideRedundantPrefabReferencesInAssets = false;
public bool hideRedundantPrefabReferencesInScenes = false;
public bool noAssetDatabaseChanges = false;
public bool showDetailedProgressBar = true;
}
@@ -159,6 +164,7 @@ namespace AssetUsageDetectorNamespace
// Get the scenes that are open right now
SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null;
Scene activeScene = EditorSceneManager.GetActiveScene();
// Make sure that the AssetDatabase is up-to-date
AssetDatabase.SaveAssets();
@@ -286,10 +292,10 @@ namespace AssetUsageDetectorNamespace
if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes )
{
// Get all open (and loaded) scenes
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
if( scene.IsValid() )
Scene scene = SceneManager.GetSceneAt( i );
if( scene.IsValid() && scene.isLoaded )
scenesToSearch.Add( scene.path );
}
}
@@ -311,10 +317,10 @@ namespace AssetUsageDetectorNamespace
if( isInPlayMode )
{
HashSet<string> openScenes = new HashSet<string>();
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
if( scene.IsValid() )
Scene scene = SceneManager.GetSceneAt( i );
if( scene.IsValid() && scene.isLoaded )
openScenes.Add( scene.path );
}
@@ -347,7 +353,7 @@ namespace AssetUsageDetectorNamespace
// Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet )
searchedUnityObjects.Add( obj.GetHashCode(), PopReferenceNode( obj ) );
searchedUnityObjects.Add( obj.GetInstanceID(), PopReferenceNode( obj ) );
// Progressbar values
int searchProgress = 0;
@@ -448,7 +454,7 @@ namespace AssetUsageDetectorNamespace
}
// If a reference is found in the Project view, save the results
if( currentSearchResultGroup.NumberOfReferences > 0 )
if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup );
}
@@ -473,7 +479,7 @@ namespace AssetUsageDetectorNamespace
}
}
if( currentSearchResultGroup.NumberOfReferences > 0 )
if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup );
}
@@ -509,19 +515,30 @@ namespace AssetUsageDetectorNamespace
}
}
// Search scenes for references
foreach( string scenePath in scenesToSearch )
{
if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) )
throw new Exception( "Search aborted" );
// Search scene for references
if( string.IsNullOrEmpty( scenePath ) )
continue;
if( excludedScenesPathsSet.Contains( scenePath ) )
continue;
SearchScene( scenePath, searchResult, searchParameters.lazySceneSearch, initialSceneSetup );
#if UNITY_2019_2_OR_NEWER
// Skip scenes in read-only packages (Issue #36)
// Credit: https://forum.unity.com/threads/check-if-asset-inside-package-is-readonly.900902/#post-5990822
if( !scenePath.StartsWithFast( "Assets/" ) )
{
var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath( scenePath );
if( packageInfo != null && packageInfo.source != UnityEditor.PackageManager.PackageSource.Embedded && packageInfo.source != UnityEditor.PackageManager.PackageSource.Local )
continue;
}
#endif
SearchScene( scenePath, searchResult, searchParameters, initialSceneSetup );
}
}
@@ -537,7 +554,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < rootGameObjects.Length; i++ )
SearchGameObjectRecursively( rootGameObjects[i] );
if( currentSearchResultGroup.NumberOfReferences > 0 )
if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup );
}
@@ -604,6 +621,10 @@ namespace AssetUsageDetectorNamespace
EditorUtility.ClearProgressBar();
// If the active scene was changed during search, reset it
if( EditorSceneManager.GetActiveScene() != activeScene )
EditorSceneManager.SetActiveScene( activeScene );
#if UNITY_2018_3_OR_NEWER
// If a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed
if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) )
@@ -642,7 +663,7 @@ namespace AssetUsageDetectorNamespace
searchResult[i].InitializeNodes( objectsToSearchSet );
// Remove empty search result groups
if( !searchResult[i].PendingSearch && searchResult[i].NumberOfReferences == 0 )
if( !searchResult[i].PendingSearch && !searchResult[i].AnyReferencesFound )
searchResult.RemoveAt( i-- );
}
}
@@ -669,7 +690,7 @@ namespace AssetUsageDetectorNamespace
else
{
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent )
usedObjectPathsSet.Add( parent.gameObject.GetHashCode().ToString() );
usedObjectPathsSet.Add( parent.gameObject.GetInstanceID().ToString() );
}
}
}
@@ -691,6 +712,19 @@ namespace AssetUsageDetectorNamespace
continue;
string assetPath = AssetDatabase.GetAssetPath( obj );
// Omit unused sub-assets whose parent assets are used (configurable via Settings)
if( AssetUsageDetectorSettings.MarkUsedAssetsSubAssetsAsUsed && AssetDatabase.IsSubAsset( obj ) && usedObjectsSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) )
continue;
// Omit meshes of an imported model asset
if( obj is Mesh && !string.IsNullOrEmpty( assetPath ) && AssetDatabase.GetMainAssetTypeAtPath( assetPath ) == typeof( GameObject ) && objectsToSearchSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) )
continue;
// Omit MonoScripts whose types can't be determined
if( obj is MonoScript && ( (MonoScript) obj ).GetClass() == null )
continue;
GameObject searchedTopmostGameObject = null;
if( obj is GameObject )
{
@@ -718,14 +752,6 @@ namespace AssetUsageDetectorNamespace
continue;
}
// Omit meshes of an imported model asset
if( obj is Mesh && !string.IsNullOrEmpty( assetPath ) && AssetDatabase.GetMainAssetTypeAtPath( assetPath ) == typeof( GameObject ) && objectsToSearchSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) )
continue;
// Omit MonoScripts whose types can't be determined
if( obj is MonoScript && ( (MonoScript) obj ).GetClass() == null )
continue;
// Use new ReferenceNodes in UnusedObjects search result group because we don't want these nodes to be linked to the actual ReferenceNodes in any way
// (i.e. we don't use actual ReferenceNodes of these objects (GetReferenceNode) because these may have links to other nodes in unknown circumstances)
ReferenceNode node = PopReferenceNode( obj );
@@ -736,13 +762,13 @@ namespace AssetUsageDetectorNamespace
if( !searchedTopmostGameObject )
{
if( obj is GameObject )
unusedMainObjectNodes[obj.GetHashCode().ToString()] = node;
unusedMainObjectNodes[obj.GetInstanceID().ToString()] = node;
else
currentSearchResultGroup.AddReference( node );
}
else // List child GameObject scene objects under their parent GameObject
{
string dictionaryKey = searchedTopmostGameObject.GetHashCode().ToString();
string dictionaryKey = searchedTopmostGameObject.GetInstanceID().ToString();
List<ReferenceNode> unusedSubObjectNodesAtPath;
if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) )
unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
@@ -892,7 +918,7 @@ namespace AssetUsageDetectorNamespace
}
// Search a scene for references
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, bool lazySearch, SceneSetup[] initialSceneSetup )
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, Parameters searchParameters, SceneSetup[] initialSceneSetup )
{
Scene scene = EditorSceneManager.GetSceneByPath( scenePath );
if( isInPlayMode && !scene.isLoaded )
@@ -908,7 +934,7 @@ namespace AssetUsageDetectorNamespace
if( !scene.isLoaded )
{
if( lazySearch )
if( searchParameters.lazySceneSearch )
{
searchResult.Add( new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene, true, true ) );
return;
@@ -924,6 +950,16 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < rootGameObjects.Length; i++ )
SearchGameObjectRecursively( rootGameObjects[i] );
// Search through Lighting Settings (it requires changing the active scene but don't do that in play mode)
if( searchParameters.searchInSceneLightingSettings && ( !isInPlayMode || SceneManager.GetActiveScene() == scene ) )
{
if( !isInPlayMode && EditorSceneManager.GetActiveScene() != scene )
EditorSceneManager.SetActiveScene( scene );
BeginSearchObject( lightmapSettingsGetter() );
BeginSearchObject( renderSettingsGetter() );
}
// If no references are found in the scene and if the scene is not part of the initial scene setup, close it
if( currentSearchResultGroup.NumberOfReferences == 0 )
{
@@ -946,11 +982,9 @@ namespace AssetUsageDetectorNamespace
EditorSceneManager.CloseScene( scene, true );
}
}
else
{
// Some references are found in this scene, save the results
if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup );
}
}
// Search a GameObject and its children for references recursively
@@ -982,9 +1016,13 @@ namespace AssetUsageDetectorNamespace
if( obj == null || obj.Equals( null ) )
return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack
if( callStack.ContainsFast( obj ) )
return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack (initially, I was using callStack.ContainsFast
// here but it returned false for objects that do exist in the call stack if VFX Graph window was open)
for( int i = callStack.Count - 1; i >= 0; i-- )
{
if( callStack[i].Equals( obj ) )
return null;
}
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
@@ -1009,14 +1047,14 @@ namespace AssetUsageDetectorNamespace
{
if( assetsToSearchSet.Count == 0 )
{
searchedUnityObjects.Add( unityObject.GetHashCode(), null );
searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null;
}
assetPath = AssetDatabase.GetAssetPath( unityObject );
if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) )
{
searchedUnityObjects.Add( unityObject.GetHashCode(), null );
searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null;
}
}
@@ -1024,7 +1062,7 @@ namespace AssetUsageDetectorNamespace
callStack.Add( unityObject );
// Search the Object in detail
Func<Object, ReferenceNode> searchFunction;
Func<object, ReferenceNode> 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 ) )
@@ -1086,13 +1124,13 @@ namespace AssetUsageDetectorNamespace
if( !searchingSourceAsset )
{
if( obj is Object )
searchedUnityObjects.Add( unityObject.GetHashCode(), result );
searchedUnityObjects.Add( unityObject.GetInstanceID(), result );
else
searchedObjects.Add( GetNodeObjectHash( obj ), result );
}
else if( result != null )
{
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetHashCode()] );
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetInstanceID()] );
PoolReferenceNode( result );
}
}
@@ -1103,6 +1141,11 @@ namespace AssetUsageDetectorNamespace
// Check if the asset at specified path depends on any of the references
private bool AssetHasAnyReference( string assetPath )
{
#if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport )
return true;
#endif
if( assetsToSearchPathsSet.Contains( assetPath ) )
return true;
@@ -1221,7 +1264,7 @@ namespace AssetUsageDetectorNamespace
{
if( nodeObject is Object )
{
if( searchedUnityObjects.TryGetValue( nodeObject.GetHashCode(), out referenceNode ) )
if( searchedUnityObjects.TryGetValue( ( (Object) nodeObject ).GetInstanceID(), out referenceNode ) )
return true;
}
else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) )
@@ -1237,7 +1280,7 @@ namespace AssetUsageDetectorNamespace
ReferenceNode result;
if( nodeObject is Object )
{
int hash = nodeObject.GetHashCode();
int hash = ( (Object) nodeObject ).GetInstanceID();
if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null )
{
result = PopReferenceNode( nodeObject );
@@ -21,6 +21,9 @@ using UnityEditor.Compilation;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.Tilemaps;
#endif
#if ASSET_USAGE_ADDRESSABLES
using UnityEngine.AddressableAssets;
#endif
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
@@ -158,9 +161,9 @@ namespace AssetUsageDetectorNamespace
#endregion
// Dictionary to quickly find the function to search a specific type with
private Dictionary<Type, Func<Object, ReferenceNode>> typeToSearchFunction;
private Dictionary<Type, Func<object, ReferenceNode>> typeToSearchFunction;
// Dictionary to associate special file extensions with their search functions
private Dictionary<string, Func<Object, ReferenceNode>> extensionToSearchFunction;
private Dictionary<string, Func<object, ReferenceNode>> extensionToSearchFunction;
// An optimization to fetch & filter fields and properties of a class only once
private readonly Dictionary<Type, VariableGetterHolder[]> typeToVariables = new Dictionary<Type, VariableGetterHolder[]>( 4096 );
@@ -196,13 +199,35 @@ namespace AssetUsageDetectorNamespace
// Unity's internal function that returns a SerializedProperty's corresponding FieldInfo
private delegate FieldInfo FieldInfoGetter( SerializedProperty p, out Type t );
private FieldInfoGetter fieldInfoGetter;
#if UNITY_2019_3_OR_NEWER
private readonly FieldInfoGetter fieldInfoGetter = (FieldInfoGetter) Delegate.CreateDelegate( typeof( FieldInfoGetter ), typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoAndStaticTypeFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#else
private readonly FieldInfoGetter fieldInfoGetter = (FieldInfoGetter) Delegate.CreateDelegate( typeof( FieldInfoGetter ), typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#endif
private readonly Func<Object> lightmapSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( LightmapEditorSettings ).GetMethod( "GetLightmapSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly Func<Object> renderSettingsGetter = (Func<Object>) Delegate.CreateDelegate( typeof( Func<Object> ), typeof( RenderSettings ).GetMethod( "GetRenderSettings", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#if UNITY_2021_2_OR_NEWER
private readonly Func<Cubemap> defaultReflectionProbeGetter = (Func<Cubemap>) Delegate.CreateDelegate( typeof( Func<Cubemap> ), typeof( RenderSettings ).GetProperty( "defaultReflection", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).GetGetMethod( true ) );
#endif
#if ASSET_USAGE_ADDRESSABLES
private readonly Func<SpriteAtlas, Sprite[]> spriteAtlasPackedSpritesGetter = (Func<SpriteAtlas, Sprite[]>) Delegate.CreateDelegate( typeof( Func<SpriteAtlas, Sprite[]> ), typeof( SpriteAtlasExtensions ).GetMethod( "GetPackedSprites", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly PropertyInfo assetReferenceSubObjectTypeGetter = typeof( AssetReference ).GetProperty( "SubOjbectType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
#endif
#if ASSET_USAGE_VFX_GRAPH
private static Type vfxResourceType => typeof( Editor ).Assembly.GetType( "UnityEditor.VFX.VisualEffectResource" ) ?? Array.Find( AppDomain.CurrentDomain.GetAssemblies(), ( assembly ) => assembly.GetName().Name == "UnityEditor.VFXModule" ).GetType( "UnityEditor.VFX.VisualEffectResource" );
private readonly Func<string, object> vfxResourceGetter = (Func<string, object>) Delegate.CreateDelegate( typeof( Func<string, object> ), vfxResourceType.GetMethod( "GetResourceAtPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private readonly MethodInfo vfxResourceContentsGetter = vfxResourceType.GetMethod( "GetContents", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
private readonly MethodInfo vfxSerializableObjectValueGetter = Array.Find( Array.Find( AppDomain.CurrentDomain.GetAssemblies(), ( assembly ) => assembly.GetName().Name == "Unity.VisualEffectGraph.Editor" ).GetType( "UnityEditor.VFX.VFXSerializableObject" ).GetMethods( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ), ( methodInfo ) => methodInfo.Name == "Get" && !methodInfo.IsGenericMethod );
#endif
private void InitializeSearchFunctionsData( Parameters searchParameters )
{
if( typeToSearchFunction == null )
{
typeToSearchFunction = new Dictionary<Type, Func<Object, ReferenceNode>>()
typeToSearchFunction = new Dictionary<Type, Func<object, ReferenceNode>>()
{
{ typeof( GameObject ), SearchGameObject },
{ typeof( Material ), SearchMaterial },
@@ -216,6 +241,9 @@ namespace AssetUsageDetectorNamespace
{ typeof( AnimatorStateTransition ), SearchAnimatorStateTransition },
{ typeof( BlendTree ), SearchBlendTree },
{ typeof( AnimationClip ), SearchAnimationClip },
{ typeof( TerrainData ), SearchTerrainData },
{ typeof( LightmapSettings ), SearchLightmapSettings },
{ typeof( RenderSettings ), SearchRenderSettings },
#if UNITY_2017_1_OR_NEWER
{ typeof( SpriteAtlas ), SearchSpriteAtlas },
#endif
@@ -224,7 +252,7 @@ namespace AssetUsageDetectorNamespace
if( extensionToSearchFunction == null )
{
extensionToSearchFunction = new Dictionary<string, Func<Object, ReferenceNode>>()
extensionToSearchFunction = new Dictionary<string, Func<object, ReferenceNode>>()
{
{ "compute", SearchShaderSecondaryAsset },
{ "cginc", SearchShaderSecondaryAsset },
@@ -240,6 +268,11 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2018_1_OR_NEWER
{ "shadergraph", SearchShaderGraph },
{ "shadersubgraph", SearchShaderGraph },
#endif
#if ASSET_USAGE_VFX_GRAPH
{ "vfx", SearchVFXGraphAsset },
{ "vfxoperator", SearchVFXGraphAsset },
{ "vfxblock", SearchVFXGraphAsset },
#endif
};
}
@@ -261,6 +294,9 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2018_1_OR_NEWER
searchShaderGraphsForSubGraphs = false;
#endif
#if ASSET_USAGE_VFX_GRAPH
bool searchVFXGraphs = false;
#endif
foreach( Object obj in objectsToSearchSet )
{
@@ -282,6 +318,10 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2017_3_OR_NEWER
else if( obj is UnityEditorInternal.AssemblyDefinitionAsset )
assemblyDefinitionFilesToSearch[AssetDatabase.GetAssetPath( obj )] = obj;
#endif
#if ASSET_USAGE_VFX_GRAPH
else if( !searchVFXGraphs && ( obj is Shader || obj is Mesh || obj.GetType().Name.StartsWithFast( "PointCache" ) || obj.GetType().Name == "ShaderGraphVfxAsset" ) )
searchVFXGraphs = true;
#endif
}
@@ -339,32 +379,39 @@ namespace AssetUsageDetectorNamespace
}
#endif
#if UNITY_2019_3_OR_NEWER
MethodInfo fieldInfoGetterMethod = typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoAndStaticTypeFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
#else
MethodInfo fieldInfoGetterMethod = typeof( Editor ).Assembly.GetType( "UnityEditor.ScriptAttributeUtility" ).GetMethod( "GetFieldInfoFromProperty", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );
#if ASSET_USAGE_VFX_GRAPH
if( searchTextureReferences || searchVFXGraphs )
{
alwaysSearchedExtensionsSet.Add( "vfx" );
alwaysSearchedExtensionsSet.Add( "vfxoperator" );
alwaysSearchedExtensionsSet.Add( "vfxblock" );
}
#endif
fieldInfoGetter = (FieldInfoGetter) Delegate.CreateDelegate( typeof( FieldInfoGetter ), fieldInfoGetterMethod );
}
private ReferenceNode SearchGameObject( Object unityObject )
private ReferenceNode SearchGameObject( object obj )
{
GameObject go = (GameObject) unityObject;
GameObject go = (GameObject) obj;
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 = go;
while( prefab = PrefabUtility.GetCorrespondingObjectFromSource( prefab ) )
#else
Object prefab = PrefabUtility.GetPrefabParent( go );
if( prefab )
#endif
bool? skipFurtherPrefabReferences = null;
for( GameObject goPrefab = go.GetPrefabParent(), prefab = goPrefab; prefab != null; prefab = prefab.GetPrefabParent() )
{
if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab as GameObject ) )
if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab ) )
{
if( goPrefab != prefab && !skipFurtherPrefabReferences.HasValue )
{
skipFurtherPrefabReferences = ShouldExcludeRedundantPrefabReferences( go ) && !go.HasAnyPrefabOverrides();
if( skipFurtherPrefabReferences.Value )
{
currentSearchResultGroup.NumberOfRedundantReferences++;
break;
}
}
referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" );
if( searchParameters.searchRefactoring != null )
@@ -381,9 +428,9 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchComponent( Object unityObject )
private ReferenceNode SearchComponent( object obj )
{
Component component = (Component) unityObject;
Component component = (Component) obj;
// Ignore Transform component (no object field to search for)
if( component is Transform )
@@ -398,10 +445,15 @@ namespace AssetUsageDetectorNamespace
MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component );
if( objectsToSearchSet.Contains( script ) )
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( ShouldExcludeRedundantPrefabReferences( component ) && !component.HasAnyPrefabOverrides() )
currentSearchResultGroup.NumberOfRedundantReferences++;
else
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( component.gameObject, script, component ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( component.gameObject, script, component ) );
}
}
}
@@ -594,11 +646,11 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchMaterial( Object unityObject )
private ReferenceNode SearchMaterial( object obj )
{
const string TEXTURE_PROPERTY_PREFIX = "m_SavedProperties.m_TexEnvs[";
Material material = (Material) unityObject;
Material material = (Material) obj;
ReferenceNode referenceNode = PopReferenceNode( material );
// We used to search only the shader and the Texture properties in this function but it has changed for 2 major reasons:
@@ -673,14 +725,14 @@ namespace AssetUsageDetectorNamespace
}
// Searches default Texture values assigned to shader properties, as well as #include references in shader source code
private ReferenceNode SearchShader( Object unityObject )
private ReferenceNode SearchShader( object obj )
{
Shader shader = (Shader) unityObject;
Shader shader = (Shader) obj;
ReferenceNode referenceNode = PopReferenceNode( shader );
if( searchTextureReferences )
{
ShaderImporter shaderImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as ShaderImporter;
ShaderImporter shaderImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( shader ) ) as ShaderImporter;
if( shaderImporter != null )
{
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
@@ -715,20 +767,20 @@ namespace AssetUsageDetectorNamespace
}
// Searches .compute, .cginc, .cg, .hlsl and .glslinc assets for #include references
private ReferenceNode SearchShaderSecondaryAsset( Object unityObject )
private ReferenceNode SearchShaderSecondaryAsset( object obj )
{
if( shaderIncludesToSearchSet.Count == 0 )
return null;
ReferenceNode referenceNode = PopReferenceNode( unityObject );
ReferenceNode referenceNode = PopReferenceNode( obj );
SearchShaderSourceCodeForCGIncludes( referenceNode );
return referenceNode;
}
// Searches class/interface inheritances and default UnityEngine.Object values assigned to script variables
private ReferenceNode SearchMonoScript( Object unityObject )
private ReferenceNode SearchMonoScript( object obj )
{
MonoScript script = (MonoScript) unityObject;
MonoScript script = (MonoScript) obj;
Type scriptType = script.GetClass();
if( scriptType == null || ( !scriptType.IsSubclassOf( typeof( MonoBehaviour ) ) && !scriptType.IsSubclassOf( typeof( ScriptableObject ) ) ) )
return null;
@@ -742,7 +794,7 @@ namespace AssetUsageDetectorNamespace
referenceNode.AddLinkTo( GetReferenceNode( monoScriptsToSearch[i] ), monoScriptsToSearchTypes[i].IsInterface ? "Implements interface" : "Extends class" );
}
MonoImporter scriptImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as MonoImporter;
MonoImporter scriptImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( script ) ) as MonoImporter;
if( scriptImporter != null )
{
VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType );
@@ -765,9 +817,9 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchAnimatorController( Object unityObject )
private ReferenceNode SearchAnimatorController( object obj )
{
RuntimeAnimatorController controller = (RuntimeAnimatorController) unityObject;
RuntimeAnimatorController controller = (RuntimeAnimatorController) obj;
ReferenceNode referenceNode = PopReferenceNode( controller );
if( controller is AnimatorController )
@@ -829,9 +881,9 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchAnimatorStateMachine( Object unityObject )
private ReferenceNode SearchAnimatorStateMachine( object obj )
{
AnimatorStateMachine animatorStateMachine = (AnimatorStateMachine) unityObject;
AnimatorStateMachine animatorStateMachine = (AnimatorStateMachine) obj;
ReferenceNode referenceNode = PopReferenceNode( animatorStateMachine );
ChildAnimatorStateMachine[] stateMachines = animatorStateMachine.stateMachines;
@@ -861,9 +913,9 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchAnimatorState( Object unityObject )
private ReferenceNode SearchAnimatorState( object obj )
{
AnimatorState animatorState = (AnimatorState) unityObject;
AnimatorState animatorState = (AnimatorState) obj;
ReferenceNode referenceNode = PopReferenceNode( animatorState );
referenceNode.AddLinkTo( SearchObject( animatorState.motion ), "Motion" );
@@ -890,15 +942,15 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchAnimatorStateTransition( Object unityObject )
private ReferenceNode SearchAnimatorStateTransition( object obj )
{
// Don't search AnimatorStateTransition objects, it will just return duplicate results of SearchAnimatorStateMachine
return PopReferenceNode( unityObject );
return PopReferenceNode( obj );
}
private ReferenceNode SearchBlendTree( Object unityObject )
private ReferenceNode SearchBlendTree( object obj )
{
BlendTree blendTree = (BlendTree) unityObject;
BlendTree blendTree = (BlendTree) obj;
ReferenceNode referenceNode = PopReferenceNode( blendTree );
ChildMotion[] children = blendTree.children;
@@ -913,9 +965,9 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
private ReferenceNode SearchAnimationClip( Object unityObject )
private ReferenceNode SearchAnimationClip( object obj )
{
AnimationClip clip = (AnimationClip) unityObject;
AnimationClip clip = (AnimationClip) obj;
ReferenceNode referenceNode = PopReferenceNode( clip );
// Get all curves from animation clip
@@ -966,10 +1018,48 @@ namespace AssetUsageDetectorNamespace
return referenceNode;
}
#if UNITY_2017_1_OR_NEWER
private ReferenceNode SearchSpriteAtlas( Object unityObject )
// TerrainData's properties like tree/detail/layer definitions aren't exposed to SerializedObject so use reflection instead
private ReferenceNode SearchTerrainData( object obj )
{
SpriteAtlas spriteAtlas = (SpriteAtlas) unityObject;
ReferenceNode referenceNode = PopReferenceNode( obj );
SearchVariablesWithReflection( referenceNode );
return referenceNode;
}
private ReferenceNode SearchLightmapSettings( object obj )
{
ReferenceNode referenceNode = PopReferenceNode( obj );
referenceNode.AddLinkTo( SearchObject( LightmapSettings.lightProbes ), "Light Probes" );
LightmapData[] lightmaps = LightmapSettings.lightmaps;
if( lightmaps != null )
{
for( int i = 0; i < lightmaps.Length; i++ )
referenceNode.AddLinkTo( SearchObject( lightmaps[i] ), "Lightmap" );
}
SearchVariablesWithSerializedObject( referenceNode, true );
return referenceNode;
}
private ReferenceNode SearchRenderSettings( object obj )
{
ReferenceNode referenceNode = PopReferenceNode( obj );
#if UNITY_2021_2_OR_NEWER
referenceNode.AddLinkTo( SearchObject( defaultReflectionProbeGetter() ), "Default Reflection Probe" );
#else
referenceNode.AddLinkTo( SearchObject( ReflectionProbe.defaultTexture ), "Default Reflection Probe" );
#endif
SearchVariablesWithSerializedObject( referenceNode, true );
return referenceNode;
}
#if UNITY_2017_1_OR_NEWER
private ReferenceNode SearchSpriteAtlas( object obj )
{
SpriteAtlas spriteAtlas = (SpriteAtlas) obj;
ReferenceNode referenceNode = PopReferenceNode( spriteAtlas );
SerializedObject spriteAtlasSO = new SerializedObject( spriteAtlas );
@@ -1059,13 +1149,13 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2017_3_OR_NEWER
// Find references from an Assembly Definition File to its Assembly Definition References
private ReferenceNode SearchAssemblyDefinitionFile( Object unityObject )
private ReferenceNode SearchAssemblyDefinitionFile( object obj )
{
if( assemblyDefinitionFilesToSearch.Count == 0 )
return null;
AssemblyDefinitionReferences assemblyDefinitionFile = JsonUtility.FromJson<AssemblyDefinitionReferences>( ( (TextAsset) unityObject ).text );
ReferenceNode referenceNode = PopReferenceNode( unityObject );
AssemblyDefinitionReferences assemblyDefinitionFile = JsonUtility.FromJson<AssemblyDefinitionReferences>( ( (TextAsset) obj ).text );
ReferenceNode referenceNode = PopReferenceNode( obj );
if( !string.IsNullOrEmpty( assemblyDefinitionFile.reference ) )
{
@@ -1099,20 +1189,20 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2018_1_OR_NEWER
// Searches Shader Graph assets for references
private ReferenceNode SearchShaderGraph( Object unityObject )
private ReferenceNode SearchShaderGraph( object obj )
{
if( !searchTextureReferences && !searchShaderGraphsForSubGraphs && shaderIncludesToSearchSet.Count == 0 )
return null;
ReferenceNode referenceNode = PopReferenceNode( unityObject );
ReferenceNode referenceNode = PopReferenceNode( obj );
// Shader Graph assets are JSON files, they must be crawled manually to find references
string graphJson = File.ReadAllText( AssetDatabase.GetAssetPath( unityObject ) );
string graphJson = File.ReadAllText( AssetDatabase.GetAssetPath( (Object) obj ) );
if( graphJson.IndexOf( "\"m_ObjectId\"", 0, Mathf.Min( 200, graphJson.Length ) ) >= 0 )
{
// New Shader Graph serialization format is used: https://github.com/Unity-Technologies/Graphics/pull/222
// Iterate over all these occurrences: "guid\": \"GUID_VALUE\" (\" is used instead of " because it is a nested JSON)
IterateOverValuesInString( graphJson, "\"guid\\\"", '"', ( guid ) =>
IterateOverValuesInString( graphJson, new string[] { "\"guid\\\"" }, '"', ( guid ) =>
{
if( guid.Length > 1 )
{
@@ -1132,7 +1222,7 @@ namespace AssetUsageDetectorNamespace
if( shaderIncludesToSearchSet.Count > 0 )
{
// Iterate over all these occurrences: "m_FunctionSource": "GUID_VALUE" (this one is not nested JSON)
IterateOverValuesInString( graphJson, "\"m_FunctionSource\"", '"', ( guid ) =>
IterateOverValuesInString( graphJson, new string[] { "\"m_FunctionSource\"" }, '"', ( guid ) =>
{
string referencePath = AssetDatabase.GUIDToAssetPath( guid );
if( !string.IsNullOrEmpty( referencePath ) && assetsToSearchPathsSet.Contains( referencePath ) )
@@ -1228,6 +1318,19 @@ namespace AssetUsageDetectorNamespace
}
#endif
#if ASSET_USAGE_VFX_GRAPH
private ReferenceNode SearchVFXGraphAsset( object obj )
{
ReferenceNode referenceNode = PopReferenceNode( obj );
object vfxResource = vfxResourceGetter( AssetDatabase.GetAssetPath( (Object) obj ) );
foreach( Object vfxResourceContent in (Object[]) vfxResourceContentsGetter.Invoke( vfxResource, null ) )
referenceNode.AddLinkTo( SearchObject( vfxResourceContent ) );
return referenceNode;
}
#endif
// Find references from an Animation/Animator component to the objects that it animates
private void SearchAnimatedObjects( ReferenceNode referenceNode )
{
@@ -1315,8 +1418,8 @@ namespace AssetUsageDetectorNamespace
{
string shaderPath = AssetDatabase.GetAssetPath( (Object) referenceNode.nodeObject );
// Iterate over all these occurrences: #include: "INCLUDE_REFERENCE"
IterateOverValuesInString( File.ReadAllText( shaderPath ), "#include ", '"', ( include ) =>
// Iterate over all these occurrences: #include "INCLUDE_REFERENCE" or #include_with_pragmas "INCLUDE_REFERENCE"
IterateOverValuesInString( File.ReadAllText( shaderPath ), new string[] { "#include ", "#include_with_pragmas " }, '"', ( include ) =>
{
bool isIncludePotentialReference = shaderIncludesToSearchSet.Contains( include );
if( !isIncludePotentialReference )
@@ -1342,83 +1445,125 @@ namespace AssetUsageDetectorNamespace
}
// Search through variables of an object with SerializedObject
private void SearchVariablesWithSerializedObject( ReferenceNode referenceNode )
private void SearchVariablesWithSerializedObject( ReferenceNode referenceNode, bool forceUseSerializedObject = false )
{
if( !isInPlayMode || referenceNode.nodeObject.IsAsset() )
Object unityObject = (Object) referenceNode.nodeObject;
if( !isInPlayMode || unityObject.IsAsset() || forceUseSerializedObject )
{
SerializedObject so = new SerializedObject( (Object) referenceNode.nodeObject );
#if ASSET_USAGE_ADDRESSABLES
// See: https://github.com/yasirkula/UnityAssetUsageDetector/issues/29
if( searchParameters.addressablesSupport && unityObject.name == "Deprecated EditorExtensionImpl" )
return;
#endif
SerializedObject so = new SerializedObject( unityObject );
SerializedProperty iterator = so.GetIterator();
SerializedProperty iteratorVisible = so.GetIterator();
if( iterator.Next( true ) )
{
bool iteratingVisible = iteratorVisible.NextVisible( true );
bool searchPrefabOverridesOnly = ShouldExcludeRedundantPrefabReferences( unityObject );
bool enterChildren;
do
{
// Iterate over NextVisible properties AND the properties that have corresponding FieldInfos (internal Unity
// properties don't have FieldInfos so we are skipping them, which is good because search results found in
// those properties aren't interesting and mostly confusing)
bool isVisible = iteratingVisible && SerializedProperty.EqualContents( iterator, iteratorVisible );
if( isVisible )
iteratingVisible = iteratorVisible.NextVisible( iteratorVisible.propertyType == SerializedPropertyType.Generic );
else
bool shouldMoveVisibleIterator = iteratingVisible && SerializedProperty.EqualContents( iterator, iteratorVisible );
bool isVisible = shouldMoveVisibleIterator || iterator.type == "Array";
if( !isVisible )
{
Type propFieldType;
isVisible = iterator.type == "Array" || fieldInfoGetter( iterator, out propFieldType ) != null;
isVisible = fieldInfoGetter( iterator, out propFieldType ) != null;
}
if( !isVisible )
{
enterChildren = false;
continue;
}
Object propertyValue;
ReferenceNode searchResult;
switch( iterator.propertyType )
else
{
case SerializedPropertyType.ObjectReference:
propertyValue = iterator.objectReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
case SerializedPropertyType.ExposedReference:
propertyValue = iterator.exposedReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference:
propertyValue = GetRawSerializedPropertyValue( iterator ) as Object;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
#endif
case SerializedPropertyType.Generic:
propertyValue = null;
searchResult = null;
enterChildren = true;
break;
default:
propertyValue = null;
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" ) )
Object propertyValue;
ReferenceNode searchResult;
switch( iterator.propertyType )
{
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath.Replace( ".Array.data[", "[" ) ); // "arrayVariable.Array.data[0]" becomes "arrayVariable[0]"
case SerializedPropertyType.ObjectReference:
propertyValue = iterator.objectReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
case SerializedPropertyType.ExposedReference:
propertyValue = iterator.exposedReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference:
object managedReferenceValue = GetRawSerializedPropertyValue( iterator );
propertyValue = managedReferenceValue as Object;
searchResult = SearchObject( PreferablyGameObject( managedReferenceValue ) );
enterChildren = false;
break;
#endif
case SerializedPropertyType.Generic:
{
#if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport && iterator.type.StartsWithFast( "AssetReference" ) && GetRawSerializedPropertyValue( iterator ) is AssetReference assetReference )
{
propertyValue = GetAddressablesAssetReferenceValue( assetReference );
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
}
else
#endif
#if ASSET_USAGE_VFX_GRAPH
if( vfxSerializableObjectValueGetter != null && iterator.type == "VFXSerializableObject" && GetRawSerializedPropertyValue( iterator ) is object vfxSerializableObject )
{
object vfxSerializableObjectValue = vfxSerializableObjectValueGetter.Invoke( vfxSerializableObject, null );
propertyValue = vfxSerializableObjectValue as Object;
searchResult = SearchObject( PreferablyGameObject( vfxSerializableObjectValue ) );
enterChildren = false;
}
else
#endif
{
propertyValue = null;
searchResult = null;
enterChildren = true;
}
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( (Object) referenceNode.nodeObject, propertyValue, iterator ) );
break;
}
default:
propertyValue = null;
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" ) )
{
if( searchPrefabOverridesOnly && !iterator.prefabOverride )
{
currentSearchResultGroup.NumberOfRedundantReferences++;
enterChildren = false;
}
else
{
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath.Replace( ".Array.data[", "[" ) ); // "arrayVariable.Array.data[0]" becomes "arrayVariable[0]"
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( unityObject, propertyValue, iterator ) );
}
}
}
}
if( shouldMoveVisibleIterator )
iteratingVisible = iteratorVisible.NextVisible( enterChildren );
} while( iterator.Next( enterChildren ) );
return;
@@ -1450,6 +1595,15 @@ namespace AssetUsageDetectorNamespace
// no need to have duplicate search entries
if( !( variableValue is ICollection ) )
{
#if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport && variableValue is AssetReference )
{
variableValue = GetAddressablesAssetReferenceValue( (AssetReference) variableValue );
if( variableValue == null || variableValue.Equals( null ) )
continue;
}
#endif
ReferenceNode searchResult = SearchObject( PreferablyGameObject( variableValue ) );
if( searchResult != null && searchResult != referenceNode )
{
@@ -1547,6 +1701,12 @@ namespace AssetUsageDetectorNamespace
if( field.FieldType.IsIgnoredUnityType() )
continue;
#if UNITY_2021_2_OR_NEWER
// "ref struct"s can't be accessed via reflection
if( field.FieldType.IsByRefLike )
continue;
#endif
// Additional filtering for fields:
// 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components
string fieldName = field.Name;
@@ -1581,6 +1741,12 @@ namespace AssetUsageDetectorNamespace
if( property.PropertyType.IsIgnoredUnityType() )
continue;
#if UNITY_2021_2_OR_NEWER
// "ref struct"s can't be accessed via reflection
if( property.PropertyType.IsByRefLike )
continue;
#endif
// Skip properties without a getter function
MethodInfo propertyGetter = property.GetGetMethod( true );
if( propertyGetter == null )
@@ -1617,6 +1783,10 @@ namespace AssetUsageDetectorNamespace
#endif
typeof( Collider2D ).IsAssignableFrom( currType ) ) )
continue;
// Ignore certain Material properties that are already searched via SearchMaterial function (also, if a material doesn't have a _Color or _BaseColor
// property and its "color" property is called, it logs an error to the console, so this rule helps avoid that scenario, as well)
else if( ( propertyName == "color" || propertyName == "mainTexture" ) && typeof( Material ).IsAssignableFrom( currType ) )
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;
@@ -1626,6 +1796,11 @@ namespace AssetUsageDetectorNamespace
// 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;
// Ignore "users" property of TerrainData because it returns the Terrains in the scene that use that TerrainData. This causes issues with callStack because TerrainData
// is already in callStack when Terrains are searched via "users" property of it and hence, Terrain->TerrainData references for that TerrainData can't be found in scenes
// (this is how callStack works, it prevents searching an object if it's already in callStack to avoid infinite recursion)
else if( propertyName == "users" && typeof( TerrainData ).IsAssignableFrom( currType ) )
continue;
else
{
VariableGetVal getter = property.CreateGetter();
@@ -1723,29 +1898,76 @@ namespace AssetUsageDetectorNamespace
return enumerator.Current;
}
#if ASSET_USAGE_ADDRESSABLES
private Object GetAddressablesAssetReferenceValue( AssetReference assetReference )
{
Object result = assetReference.editorAsset;
if( !result )
return null;
string subObjectName = assetReference.SubObjectName;
if( !string.IsNullOrEmpty( subObjectName ) )
{
if( result is SpriteAtlas )
{
Sprite[] packedSprites = spriteAtlasPackedSpritesGetter( (SpriteAtlas) result );
if( packedSprites != null )
{
for( int i = 0; i < packedSprites.Length; i++ )
{
if( packedSprites[i] && packedSprites[i].name == subObjectName )
return packedSprites[i];
}
}
}
else
{
Type subObjectType = (Type) assetReferenceSubObjectTypeGetter.GetValue( assetReference, null ) ?? typeof( Object );
Object[] subAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( result ) );
for( int k = 0; k < subAssets.Length; k++ )
{
if( subAssets[k] && subAssets[k].name == subObjectName && subObjectType.IsAssignableFrom( subAssets[k].GetType() ) )
return subAssets[k];
}
}
}
return result;
}
#endif
private bool ShouldExcludeRedundantPrefabReferences( Object obj )
{
return ( ( searchParameters.hideRedundantPrefabReferencesInAssets && obj.IsAsset() ) || ( searchParameters.hideRedundantPrefabReferencesInScenes && !obj.IsAsset() ) ) && obj.GetPrefabParent() != null;
}
// Iterates over all occurrences of specific key-value pairs in string
// Example1: #include "VALUE" valuePrefix=#include, valueWrapperChar="
// Example2: "guid": "VALUE" valuePrefix="guid", valueWrapperChar="
private void IterateOverValuesInString( string str, string valuePrefix, char valueWrapperChar, Action<string> valueAction )
private void IterateOverValuesInString( string str, string[] valuePrefixes, char valueWrapperChar, Action<string> valueAction )
{
int valueStartIndex, valueEndIndex = 0;
while( true )
for( int i = 0; i < valuePrefixes.Length; i++ )
{
valueStartIndex = str.IndexOf( valuePrefix, valueEndIndex );
if( valueStartIndex < 0 )
return;
string valuePrefix = valuePrefixes[i];
int valueStartIndex, valueEndIndex = 0;
while( true )
{
valueStartIndex = str.IndexOf( valuePrefix, valueEndIndex );
if( valueStartIndex < 0 )
break;
valueStartIndex = str.IndexOf( valueWrapperChar, valueStartIndex + valuePrefix.Length );
if( valueStartIndex < 0 )
return;
valueStartIndex = str.IndexOf( valueWrapperChar, valueStartIndex + valuePrefix.Length );
if( valueStartIndex < 0 )
break;
valueStartIndex++;
valueEndIndex = str.IndexOf( valueWrapperChar, valueStartIndex );
if( valueEndIndex < 0 )
return;
valueStartIndex++;
valueEndIndex = str.IndexOf( valueWrapperChar, valueStartIndex );
if( valueEndIndex < 0 )
break;
if( valueEndIndex > valueStartIndex )
valueAction( str.Substring( valueStartIndex, valueEndIndex - valueStartIndex ) );
if( valueEndIndex > valueStartIndex )
valueAction( str.Substring( valueStartIndex, valueEndIndex - valueStartIndex ) );
}
}
}
@@ -96,6 +96,13 @@ namespace AssetUsageDetectorNamespace
#endregion
#region Other Settings
private static bool? m_showRootAssetName = null;
public static bool ShowRootAssetName
{
get { if( m_showRootAssetName == null ) m_showRootAssetName = EditorPrefs.GetBool( "AUD_ShowRootAssetName", true ); return m_showRootAssetName.Value; }
set { if( m_showRootAssetName == value ) return; m_showRootAssetName = value; EditorPrefs.SetBool( "AUD_ShowRootAssetName", value ); }
}
private static bool? m_pingClickedObjects = null;
public static bool PingClickedObjects
{
@@ -117,6 +124,13 @@ namespace AssetUsageDetectorNamespace
set { if( m_selectDoubleClickedObjects == value ) return; m_selectDoubleClickedObjects = value; EditorPrefs.SetBool( "AUD_SelectDoubleClickedObj", value ); }
}
private static bool? m_markUsedAssetsSubAssetsAsUsed = null;
public static bool MarkUsedAssetsSubAssetsAsUsed
{
get { if( m_markUsedAssetsSubAssetsAsUsed == null ) m_markUsedAssetsSubAssetsAsUsed = EditorPrefs.GetBool( "AUD_MarkUsedAssetsSubAssetsAsUsed", true ); return m_markUsedAssetsSubAssetsAsUsed.Value; }
set { if( m_markUsedAssetsSubAssetsAsUsed == value ) return; m_markUsedAssetsSubAssetsAsUsed = value; EditorPrefs.SetBool( "AUD_MarkUsedAssetsSubAssetsAsUsed", value ); }
}
private static bool? m_showUnityTooltip = null;
public static bool ShowUnityTooltip
{
@@ -179,18 +193,22 @@ namespace AssetUsageDetectorNamespace
EditorGUI.BeginChangeCheck();
SettingsHeaderColor = ColorField( "Settings Header Color", SettingsHeaderColor, Color.cyan );
ShowRootAssetName = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Root Asset's Name For Sub-Assets (Requires Refresh)", ShowRootAssetName );
EditorGUILayout.Space();
PingClickedObjects = EditorGUILayout.Toggle( "Ping Clicked Objects", PingClickedObjects );
SelectClickedObjects = EditorGUILayout.Toggle( "Select Clicked Objects", SelectClickedObjects );
SelectDoubleClickedObjects = EditorGUILayout.Toggle( "Select Double Clicked Objects", SelectDoubleClickedObjects );
PingClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Ping Clicked Objects", PingClickedObjects );
SelectClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Select Clicked Objects", SelectClickedObjects );
SelectDoubleClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Select Double Clicked Objects", SelectDoubleClickedObjects );
EditorGUILayout.Space();
ShowUnityTooltip = EditorGUILayout.Toggle( "Show Unity Tooltip", ShowUnityTooltip );
ShowCustomTooltip = EditorGUILayout.Toggle( "Show Custom Tooltip", ShowCustomTooltip );
MarkUsedAssetsSubAssetsAsUsed = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Hide unused sub-assets in \"Unused Objects\" list if their parent assets are used (Requires Refresh)", MarkUsedAssetsSubAssetsAsUsed );
EditorGUILayout.Space();
ShowUnityTooltip = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Unity Tooltip", ShowUnityTooltip );
ShowCustomTooltip = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Custom Tooltip", ShowCustomTooltip );
EditorGUI.indentLevel++;
CustomTooltipDelay = FloatField( "Delay", CustomTooltipDelay, 0.7f );
EditorGUI.indentLevel--;
@@ -202,6 +220,7 @@ namespace AssetUsageDetectorNamespace
EditorGUILayout.Space();
SettingsHeaderColor = ColorField( "Settings Header Color", SettingsHeaderColor, Color.cyan );
SearchResultGroupHeaderColor = ColorField( "Group Header Color", SearchResultGroupHeaderColor, Color.cyan );
RootRowsBackgroundColor = ColorField( "Root Rows Background Color", RootRowsBackgroundColor, EditorGUIUtility.isProSkin ? new Color( 0f, 1f, 1f, 0.15f ) : new Color( 0f, 1f, 1f, 0.25f ) );
RootRowsBorderColor = ColorField( "Root Rows Border Color", RootRowsBorderColor, EditorGUIUtility.isProSkin ? new Color( 0.15f, 0.15f, 0.15f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) );
@@ -213,7 +232,7 @@ namespace AssetUsageDetectorNamespace
SelectedRowOccurrencesColor = ColorField( "Selected Row All Occurrences Tint", SelectedRowOccurrencesColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.3f, 0.75f, 1f ) : new Color( 0.25f, 0.75f, 1f, 1f ) );
SearchMatchingTextColor = ColorField( "Matching Search Text Color", SearchMatchingTextColor, Color.red );
ShowTreeLines = EditorGUILayout.Toggle( "Show Tree Lines", ShowTreeLines );
ShowTreeLines = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Tree Lines", ShowTreeLines );
EditorGUI.indentLevel++;
TreeLinesColor = ColorField( "Normal Color", TreeLinesColor, EditorGUIUtility.isProSkin ? new Color( 0.65f, 0.65f, 0.65f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) );
HighlightedTreeLinesColor = ColorField( "Highlighted Color", HighlightedTreeLinesColor, Color.cyan );
@@ -5,7 +5,10 @@ using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -19,6 +22,7 @@ namespace AssetUsageDetectorNamespace
private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew };
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
private const string PREFS_SEARCH_SCENE_LIGHTING_SETTINGS = "AUD_LightingSettingsSearch";
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
@@ -28,15 +32,29 @@ namespace AssetUsageDetectorNamespace
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
#if ASSET_USAGE_ADDRESSABLES
private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
#endif
private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks";
private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS = "AUD_HideRedundantPRefsInAssets";
private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES = "AUD_HideRedundantPRefsInScenes";
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );
private readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f );
private static readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f );
private static readonly GUIContent sharedGUIContent = new GUIContent();
private readonly GUIContent hideRedundantPrefabReferencesInAssetsLabel = new GUIContent( "Hide redundant prefab references in Assets", "Hides redundant/non-overridden references in prefab variants and nested prefabs. " +
"This will help focus on only the references that actually matter. For example:\n\n" +
"- Material CloudMat is assigned to prefab Cloud and its variant CloudBig. Since changing Cloud's material will also affect CloudBig, search results won't show CloudBig's reference" );
private readonly GUIContent hideRedundantPrefabReferencesInScenesLabel = new GUIContent( "Hide redundant prefab references in Scenes", "Hides redundant/non-overridden references in prefab instances. " +
"This will help focus on only the references that actually matter. For example:\n\n" +
"- Prefab Healthbar is nested inside prefab Player. An instance of Player exists in the current scene and its Healthbar isn't modified. Since modifying Healthbar in Player prefab will also affect " +
"the instance in the scene, search results won't show the instance in the scene while searching for Healthbar's references" );
private GUIStyle lockButtonStyle;
@@ -69,6 +87,7 @@ namespace AssetUsageDetectorNamespace
private bool searchInScenesInBuild = true; // Scenes in build
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
private bool searchInSceneLightingSettings = true; // Window-Rendering-Lighting settings
private bool searchInAssetsFolder = true; // Assets in Project window
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
@@ -80,11 +99,15 @@ namespace AssetUsageDetectorNamespace
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
private bool addressablesSupport = false;
#endif
private bool searchNonSerializableVariables = true;
private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false;
private bool hideDuplicateRows = true;
private bool hideReduntantPrefabVariantLinks = true;
private bool hideRedundantPrefabReferencesInAssets = false;
private bool hideRedundantPrefabReferencesInScenes = false;
private bool noAssetDatabaseChanges = false;
private bool showDetailedProgressBar = true;
@@ -149,6 +172,14 @@ namespace AssetUsageDetectorNamespace
objectsToSearch[i].RefreshSubAssets();
} );
}
else if( currentPhase == Phase.Complete )
{
if( searchResult != null && searchResult.NumberOfGroups > 0 )
{
contextMenu.AddSeparator( "" );
contextMenu.AddItem( new GUIContent( "Collapse All" ), false, searchResult.CollapseAllSearchResultGroups );
}
}
}
// Shows lock button at the top-right corner
@@ -298,6 +329,7 @@ namespace AssetUsageDetectorNamespace
if( searchParameters != null )
{
ParseSceneSearchMode( searchParameters.searchInScenes );
searchInSceneLightingSettings = searchParameters.searchInSceneLightingSettings;
searchInAssetsFolder = searchParameters.searchInAssetsFolder;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchInProjectSettings = searchParameters.searchInProjectSettings;
@@ -308,9 +340,13 @@ namespace AssetUsageDetectorNamespace
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch;
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = searchParameters.addressablesSupport;
#endif
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows;
hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks;
hideRedundantPrefabReferencesInAssets = searchParameters.hideRedundantPrefabReferencesInAssets;
hideRedundantPrefabReferencesInScenes = searchParameters.hideRedundantPrefabReferencesInScenes;
noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
showDetailedProgressBar = searchParameters.showDetailedProgressBar;
@@ -378,6 +414,7 @@ namespace AssetUsageDetectorNamespace
private void SavePrefs()
{
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
EditorPrefs.SetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, searchInSceneLightingSettings );
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
@@ -387,16 +424,20 @@ namespace AssetUsageDetectorNamespace
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
EditorPrefs.SetBool( PREFS_ADDRESSABLES_SUPPORT, addressablesSupport );
#endif
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
}
private void LoadPrefs()
{
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInSceneLightingSettings = EditorPrefs.GetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, true );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
@@ -406,9 +447,13 @@ namespace AssetUsageDetectorNamespace
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = EditorPrefs.GetBool( PREFS_ADDRESSABLES_SUPPORT, false );
#endif
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true );
hideRedundantPrefabReferencesInAssets = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
hideRedundantPrefabReferencesInScenes = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
}
@@ -458,7 +503,10 @@ namespace AssetUsageDetectorNamespace
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
}
else if( currentPhase == Phase.Setup )
{
@@ -466,24 +514,16 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10f );
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCH IN</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
Utilities.DrawHeader( "<b>SEARCH IN</b>" );
searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
if( searchInAssetsFolder )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
BeginIndentedGUI();
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
excludedAssetsDrawer.Draw( excludedAssets );
GUILayout.EndVertical();
GUILayout.EndHorizontal();
EndIndentedGUI();
}
GUILayout.Space( 5f );
@@ -504,13 +544,10 @@ namespace AssetUsageDetectorNamespace
if( searchInScenesInBuild )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
BeginIndentedGUI( false );
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
GUILayout.EndHorizontal();
EndIndentedGUI( false );
}
GUI.enabled = true;
@@ -518,14 +555,13 @@ namespace AssetUsageDetectorNamespace
searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes );
}
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
BeginIndentedGUI();
excludedScenesDrawer.Draw( excludedScenes );
EndIndentedGUI();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup( !searchInOpenScenes && !searchInScenesInBuild && !searchInAllScenes );
searchInSceneLightingSettings = WordWrappingToggleLeft( "Scene Lighting Settings (WARNING: This may change the active scene during search)", searchInSceneLightingSettings );
EditorGUI.EndDisabledGroup();
Utilities.DrawSeparatorLine();
@@ -533,16 +569,20 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10f );
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
Utilities.DrawHeader( "<b>SETTINGS</b>" );
#if ASSET_USAGE_ADDRESSABLES
EditorGUI.BeginDisabledGroup( addressablesSupport );
#endif
lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
EditorGUI.EndDisabledGroup();
addressablesSupport = WordWrappingToggleLeft( "Addressables support (Experimental) (WARNING: 'Lazy scene search' will be disabled) (slower search)", addressablesSupport );
#endif
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
#if UNITY_2018_3_OR_NEWER
hideReduntantPrefabVariantLinks = WordWrappingToggleLeft( "Hide redundant prefab variant links (when the same value is assigned to the same Component of a prefab and its variant(s))", hideReduntantPrefabVariantLinks );
#endif
hideRedundantPrefabReferencesInAssets = WordWrappingToggleLeft( hideRedundantPrefabReferencesInAssetsLabel, hideRedundantPrefabReferencesInAssets );
hideRedundantPrefabReferencesInScenes = WordWrappingToggleLeft( hideRedundantPrefabReferencesInScenesLabel, hideRedundantPrefabReferencesInScenes );
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar );
@@ -573,7 +613,10 @@ namespace AssetUsageDetectorNamespace
GUI.enabled = true;
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
if( searchResult == null )
{
@@ -613,10 +656,7 @@ namespace AssetUsageDetectorNamespace
private void DrawObjectsToSearchSection()
{
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCHED OBJECTS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
Utilities.DrawHeader( "<b>SEARCHED OBJECTS</b>" );
Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect();
searchedObjectsHeaderRect.x += 5f;
@@ -629,7 +669,31 @@ namespace AssetUsageDetectorNamespace
objectsToSearchDrawer.Draw( objectsToSearch );
}
private bool WordWrappingToggleLeft( string label, bool value )
private void BeginIndentedGUI( bool isVertical = true )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35f );
if( isVertical )
GUILayout.BeginVertical();
}
private void EndIndentedGUI( bool isVertical = true )
{
if( isVertical )
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
public static bool WordWrappingToggleLeft( string label, bool value )
{
sharedGUIContent.text = label;
sharedGUIContent.tooltip = null;
return WordWrappingToggleLeft( sharedGUIContent, value );
}
public static bool WordWrappingToggleLeft( GUIContent label, bool value )
{
GUILayout.BeginHorizontal();
bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 );
@@ -658,6 +722,7 @@ namespace AssetUsageDetectorNamespace
{
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
searchInScenes = GetSceneSearchMode( true ),
searchInSceneLightingSettings = searchInSceneLightingSettings,
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
@@ -670,10 +735,16 @@ namespace AssetUsageDetectorNamespace
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
#if ASSET_USAGE_ADDRESSABLES
lazySceneSearch = lazySceneSearch && !addressablesSupport,
addressablesSupport = addressablesSupport,
#else
lazySceneSearch = lazySceneSearch,
#endif
calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows,
hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks,
hideRedundantPrefabReferencesInAssets = hideRedundantPrefabReferencesInAssets,
hideRedundantPrefabReferencesInScenes = hideRedundantPrefabReferencesInScenes && searchInAssetsFolder,
noAssetDatabaseChanges = noAssetDatabaseChanges,
showDetailedProgressBar = showDetailedProgressBar
} );
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
@@ -22,6 +23,7 @@ namespace AssetUsageDetectorNamespace
public SearchResultGroup.GroupType type;
public bool isExpanded;
public bool pendingSearch;
public int redundantReferences;
public SearchResultTreeViewState treeViewState;
public List<int> initialSerializedNodes;
@@ -371,9 +373,15 @@ namespace AssetUsageDetectorNamespace
return scrollPosition;
}
public int IndexOf( SearchResultGroup searchResult )
public int IndexOf( SearchResultGroup searchResultGroup )
{
return result.IndexOf( searchResult );
return result.IndexOf( searchResultGroup );
}
public void CollapseAllSearchResultGroups()
{
for( int i = 0; i < result.Count; i++ )
result[i].Collapse();
}
public void CancelDelayedTreeViewTooltip()
@@ -569,6 +577,9 @@ namespace AssetUsageDetectorNamespace
public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } }
public int NumberOfRedundantReferences { get; internal set; }
public bool AnyReferencesFound { get { return NumberOfReferences > 0 || NumberOfRedundantReferences > 0; } }
public SearchResultGroup( string title, GroupType type, bool isExpanded = true, bool pendingSearch = false )
{
Title = title.StartsWith( "<b>" ) ? title : string.Concat( "<b>", title, "</b>" );
@@ -600,6 +611,11 @@ namespace AssetUsageDetectorNamespace
treeViewSearchField = null;
}
public void Collapse()
{
IsExpanded = false;
}
// Initializes commonly used variables of the nodes
public void InitializeNodes( HashSet<Object> objectsToSearchSet )
{
@@ -725,7 +741,7 @@ namespace AssetUsageDetectorNamespace
if( searchResult != null )
contextMenu.AddItem( new GUIContent( "Hide" ), false, () => searchResult.RemoveSearchResultGroup( this ) );
if( references.Count > 0 )
if( references.Count > 0 && treeView != null )
{
if( contextMenu.GetItemCount() > 0 )
contextMenu.AddSeparator( "" );
@@ -766,32 +782,57 @@ namespace AssetUsageDetectorNamespace
IsExpanded = true;
} );
if( searchResult != null && searchResult.NumberOfGroups > 1 && !string.IsNullOrEmpty( treeViewState.searchTerm ) )
if( !string.IsNullOrEmpty( treeViewState.searchTerm ) )
{
if( contextMenu.GetItemCount() > 0 )
contextMenu.AddSeparator( "" );
contextMenu.AddItem( new GUIContent( "Apply Search to All Results" ), false, () =>
if( searchResult != null && searchResult.NumberOfGroups > 1 )
{
for( int i = 0; i < searchResult.NumberOfGroups; i++ )
contextMenu.AddItem( new GUIContent( "Apply Search to All Results" ), false, () =>
{
if( searchResult[i].treeView == null )
continue;
for( int i = 0; i < searchResult.NumberOfGroups; i++ )
{
if( searchResult[i].treeView == null )
continue;
string previousSearchTerm = searchResult[i].treeViewState.searchTerm ?? "";
SearchResultTreeView.SearchMode previousSearchMode = searchResult[i].treeViewState.searchMode;
string previousSearchTerm = searchResult[i].treeViewState.searchTerm ?? "";
SearchResultTreeView.SearchMode previousSearchMode = searchResult[i].treeViewState.searchMode;
searchResult[i].treeViewState.searchTerm = treeViewState.searchTerm ?? "";
searchResult[i].treeViewState.searchMode = treeViewState.searchMode;
searchResult[i].treeViewState.searchTerm = treeViewState.searchTerm ?? "";
searchResult[i].treeViewState.searchMode = treeViewState.searchMode;
if( treeViewState.searchTerm != previousSearchTerm || treeViewState.searchMode != previousSearchMode )
searchResult[i].treeView.RefreshSearch( previousSearchTerm );
}
} );
if( treeViewState.searchTerm != previousSearchTerm || treeViewState.searchMode != previousSearchMode )
searchResult[i].treeView.RefreshSearch( previousSearchTerm );
}
} );
}
IList<TreeViewItem> treeViewRows = treeView.GetRows();
if( treeViewRows.Count > 1 ) // References are at depth 1 so if there are any references, at least 2 rows must exist
{
contextMenu.AddItem( new GUIContent( "Hide Search Results" ), false, () =>
{
List<int> removedRows = new List<int>( treeViewRows.Count );
for( int i = treeViewRows.Count - 1; i >= 0; i-- )
{
if( treeViewRows[i].depth > 0 )
removedRows.Add( treeViewRows[i].id );
}
treeView.ClearSearch();
treeView.HideItems( removedRows );
} );
}
}
}
if( Type == GroupType.Scene && !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 )
#if UNITY_2022_2_OR_NEWER
int loadedSceneCount = SceneManager.loadedSceneCount;
#else
int loadedSceneCount = EditorSceneManager.loadedSceneCount;
#endif
if( Type == GroupType.Scene && !EditorApplication.isPlaying && loadedSceneCount > 1 )
{
// Show context menu when SearchResultGroup's header is right clicked
Scene scene = EditorSceneManager.GetSceneByPath( ScenePath );
@@ -832,6 +873,9 @@ namespace AssetUsageDetectorNamespace
if( IsExpanded )
{
if( NumberOfRedundantReferences > 0 )
EditorGUILayout.HelpBox( string.Concat( NumberOfRedundantReferences.ToString(), " redundant prefab reference(s) were skipped. Disable \"Hide redundant prefab references in ", ( Type == GroupType.Scene || Type == GroupType.DontDestroyOnLoad ) ? "Scenes" : "Assets", "\" to see them." ), MessageType.Info );
if( PendingSearch )
GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
else if( references.Count == 0 )
@@ -846,6 +890,9 @@ namespace AssetUsageDetectorNamespace
if( searchResult != null && searchResult.SearchParameters.dontSearchInSourceAssets && searchResult.SearchParameters.objectsToSearch.Length > 1 )
EditorGUILayout.HelpBox( "'Don't search \"SEARCHED OBJECTS\" themselves for references' is enabled, some of these objects might be used by \"SEARCHED OBJECTS\".", MessageType.Warning );
if( !AssetUsageDetectorSettings.MarkUsedAssetsSubAssetsAsUsed )
EditorGUILayout.HelpBox( "'Hide unused sub-assets in \"Unused Objects\" list if their parent assets are used' is disabled, unused sub-assets' parent assets might be used.", MessageType.Warning );
EditorGUILayout.HelpBox( "Although no references to these objects are found, they might still be used somewhere (e.g. via Resources.Load). If you intend to delete these objects, consider creating a backup of your project first.", MessageType.Info );
}
@@ -861,7 +908,7 @@ namespace AssetUsageDetectorNamespace
if( shouldUpdateInitialTreeViewNodeId )
treeViewState.initialNodeId = searchResult.nextTreeViewId;
treeView = new SearchResultTreeView( treeViewState, references, ( Type == GroupType.UnusedObjects ) ? SearchResultTreeView.TreeType.UnusedObjects : SearchResultTreeView.TreeType.Normal, searchResult != null ? searchResult.UsedObjects : null, searchResult != null && searchResult.SearchParameters.hideDuplicateRows, searchResult != null && searchResult.SearchParameters.hideReduntantPrefabVariantLinks, true );
treeView = new SearchResultTreeView( treeViewState, references, ( Type == GroupType.UnusedObjects ) ? SearchResultTreeView.TreeType.UnusedObjects : SearchResultTreeView.TreeType.Normal, searchResult != null ? searchResult.UsedObjects : null, searchResult != null && searchResult.SearchParameters.hideDuplicateRows, true );
if( isFirstInitialization )
{
@@ -1025,6 +1072,7 @@ namespace AssetUsageDetectorNamespace
type = Type,
isExpanded = IsExpanded,
pendingSearch = PendingSearch,
redundantReferences = NumberOfRedundantReferences,
treeViewState = treeViewState
};
@@ -1042,6 +1090,7 @@ namespace AssetUsageDetectorNamespace
// Deserialize this result group from the serialized data
internal void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List<ReferenceNode> allNodes )
{
NumberOfRedundantReferences = serializedResultGroup.redundantReferences;
treeViewState = serializedResultGroup.treeViewState;
if( serializedResultGroup.initialSerializedNodes != null )
@@ -1163,30 +1212,6 @@ namespace AssetUsageDetectorNamespace
}
}
internal bool HasLinkToObjectWithDescriptions( int instanceId, List<string> descriptions )
{
for( int i = links.Count - 1; i >= 0; i-- )
{
Link link = links[i];
if( link.targetNode.instanceId == instanceId )
{
List<string> _descriptions = link.descriptions;
if( _descriptions.Count != descriptions.Count )
return false;
for( int j = _descriptions.Count - 1; j >= 0; j-- )
{
if( _descriptions[j] != descriptions[j] )
return false;
}
return true;
}
}
return false;
}
public void CopyReferencesTo( ReferenceNode other )
{
other.links.Clear();
@@ -1210,6 +1235,13 @@ namespace AssetUsageDetectorNamespace
{
instanceId = unityObject.GetInstanceID();
Label = unityObject.name + " (" + unityObject.GetType().Name + ")";
if( AssetUsageDetectorSettings.ShowRootAssetName && unityObject.IsAsset() && !AssetDatabase.IsMainAsset( unityObject ) )
{
string mainAssetName = Path.GetFileNameWithoutExtension( AssetDatabase.GetAssetPath( unityObject ) );
if( unityObject.name != mainAssetName )
Label += " <in " + mainAssetName + ">";
}
}
else if( nodeObject != null )
{
@@ -5,7 +5,10 @@ using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -121,7 +124,6 @@ namespace AssetUsageDetectorNamespace
private readonly TreeType treeType;
private readonly bool hideDuplicateRows;
private readonly bool hideReduntantPrefabVariantLinks;
private bool isSearching;
@@ -161,13 +163,12 @@ namespace AssetUsageDetectorNamespace
[System.Obsolete] private new string searchString { get; }
[System.Obsolete] private new bool hasSearch { get; }
public SearchResultTreeView( SearchResultTreeViewState state, List<ReferenceNode> references, TreeType treeType, HashSet<Object> usedObjectsSet, bool hideDuplicateRows, bool hideReduntantPrefabVariantLinks, bool usesExternalScrollView ) : base( state )
public SearchResultTreeView( SearchResultTreeViewState state, List<ReferenceNode> references, TreeType treeType, HashSet<Object> usedObjectsSet, bool hideDuplicateRows, bool usesExternalScrollView ) : base( state )
{
this.state = state;
this.references = references;
this.treeType = treeType;
this.hideDuplicateRows = hideDuplicateRows;
this.hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks;
highlightedSearchTextColor = "<color=#" + ColorUtility.ToHtmlStringRGBA( AssetUsageDetectorSettings.SearchMatchingTextColor ) + ">";
@@ -199,6 +200,13 @@ namespace AssetUsageDetectorNamespace
RefreshSelectedNodes( GetSelection() );
}
public void ClearSearch()
{
string prevSearchTerm = state.searchTerm;
state.searchTerm = "";
RefreshSearch( prevSearchTerm );
}
public void RefreshSearch( string prevSearchTerm )
{
bool wasSearchTermEmpty = string.IsNullOrEmpty( prevSearchTerm );
@@ -284,25 +292,6 @@ namespace AssetUsageDetectorNamespace
private bool GenerateRowsRecursive( TreeViewItem parent, ReferenceNode referenceNode, ReferenceNodeData parentData, int siblingIndex, int depth, bool? itemForcedVisibility, List<ReferenceNode> stack, HashSet<ReferenceNode> processedNodes, ref int id )
{
#if UNITY_2018_3_OR_NEWER
// If the same reference is found in both a prefab variant and its base prefab, omit the prefab variant to reduce the number of
// redundant links (changing the value in base prefab will automatically change the value in its variants, after all)
if( hideReduntantPrefabVariantLinks && depth > 0 )
{
Object unityObject = referenceNode.UnityObject;
if( unityObject && ( unityObject is Component || unityObject is GameObject ) && unityObject.IsAsset() )
{
List<string> linkDescriptions = parentData.node[siblingIndex].descriptions;
if( linkDescriptions.Count > 0 )
{
Object prefabObject = PrefabUtility.GetCorrespondingObjectFromSource( unityObject );
if( prefabObject && parentData.node.HasLinkToObjectWithDescriptions( prefabObject.GetHashCode(), linkDescriptions ) )
return false;
}
}
}
#endif
TreeViewItem item = new TreeViewItem( id++, depth, "" );
ReferenceNodeData data = new ReferenceNodeData( item, referenceNode, parentData, siblingIndex );
@@ -963,6 +952,8 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < item.children.Count; i++ )
shouldExpand |= GetMainReferenceIdsRecursive( item.children[i], ids );
}
else
shouldExpand = true; // No main reference is encountered in this branch; expand the whole branch
if( shouldExpand )
ids.Add( item.id );
@@ -1007,7 +998,7 @@ namespace AssetUsageDetectorNamespace
return referenceNodes.Contains( GetDataFromId( item.id ).node );
}
private void HideItems( IList<int> ids )
public void HideItems( IList<int> ids )
{
if( ids.Count > 0 )
{
@@ -1172,10 +1163,10 @@ namespace AssetUsageDetectorNamespace
if( selectedNodes.Count > 0 )
{
SearchResultTreeView isolatedTreeView = new SearchResultTreeView( new SearchResultTreeViewState(), selectedNodes, TreeType.IsolatedView, null, hideDuplicateRows, hideReduntantPrefabVariantLinks, false );
SearchResultTreeView isolatedTreeView = new SearchResultTreeView( new SearchResultTreeViewState(), selectedNodes, TreeType.IsolatedView, null, hideDuplicateRows, false );
isolatedTreeView.ExpandMainReferences();
SearchResultTreeViewIsolatedView.Show( new Vector2( EditorWindow.focusedWindow.position.width, isolatedTreeView.totalHeight + 1f ), isolatedTreeView, new GUIContent( selectedNodes[0].Label + ( selectedNodes.Count <= 1 ? "" : ( " (and " + ( selectedNodes.Count - 1 ) + " more)" ) ) ) );
SearchResultTreeViewIsolatedView.Show( new Vector2( EditorWindow.focusedWindow.position.width, Mathf.Max( isolatedTreeView.totalHeight, EditorGUIUtility.singleLineHeight * 5f ) + 1f ), isolatedTreeView, new GUIContent( selectedNodes[0].Label + ( selectedNodes.Count <= 1 ? "" : ( " (and " + ( selectedNodes.Count - 1 ) + " more)" ) ) ) );
}
}
@@ -1329,7 +1320,7 @@ namespace AssetUsageDetectorNamespace
SearchResultTreeViewIsolatedView window = CreateInstance<SearchResultTreeViewIsolatedView>();
window.treeView = treeView;
window.titleContent = title;
window.ShowAuxWindow();
window.Show();
window.minSize = new Vector2( 150f, Mathf.Min( preferredSize.y, EditorGUIUtility.singleLineHeight * 2f ) );
window.position = new Rect( new Vector2( -9999f, -9999f ), preferredSize );
+121 -24
View File
@@ -10,7 +10,7 @@ using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -51,6 +51,10 @@ namespace AssetUsageDetectorNamespace
private static MethodInfo screenFittedRectGetter;
#if UNITY_2018_3_OR_NEWER
private static readonly Func<Object, bool, bool> prefabHasAnyOverridesGetter = (Func<Object, bool, bool>) Delegate.CreateDelegate( typeof( Func<Object, bool, bool> ), typeof( PrefabUtility ).GetMethod( "HasObjectOverride", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#endif
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
internal static readonly StringBuilder stringBuilder = new StringBuilder( 400 );
@@ -114,6 +118,97 @@ namespace AssetUsageDetectorNamespace
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
}
public static T GetPrefabParent<T>( this T obj ) where T : Object
{
#if UNITY_2018_3_OR_NEWER
return PrefabUtility.GetCorrespondingObjectFromSource( obj );
#else
return PrefabUtility.GetPrefabParent( obj ) as T;
#endif
}
public static bool HasAnyPrefabOverrides( this Object obj )
{
if( obj.GetPrefabParent() == null )
return false;
#if UNITY_2018_3_OR_NEWER
return prefabHasAnyOverridesGetter( obj, false );
#else
SerializedProperty iterator = new SerializedObject( obj ).GetIterator();
if( iterator.Next( true ) )
{
do
{
if( iterator.prefabOverride )
return true;
} while( iterator.NextVisible( false ) );
}
return false;
#endif
}
public static bool HasAnyPrefabOverrides( this GameObject gameObject )
{
if( gameObject.GetPrefabParent() == null )
return false;
#if UNITY_2018_3_OR_NEWER
if( !PrefabUtility.HasPrefabInstanceAnyOverrides( gameObject, false ) )
return false;
#endif
Transform rootTransform = gameObject.transform;
List<Component> components = new List<Component>( 8 );
Stack<Transform> stack = new Stack<Transform>( 8 );
stack.Push( rootTransform );
while( stack.Count > 0 )
{
Transform transform = stack.Pop();
Transform prefab = transform.GetPrefabParent();
if( prefab == null ) // GameObject is added as override
return true;
if( transform.childCount != prefab.childCount ) // Has some added/destroyed children as override
return true;
bool isRootTransform = ReferenceEquals( transform, rootTransform );
if( !isRootTransform && ( transform.gameObject as Object ).HasAnyPrefabOverrides() ) // GameObject's properties are modified (e.g. name or tag) (excluding root GameObject)
return true;
components.Clear();
transform.GetComponents( components );
foreach( Component component in components )
{
if( component == null )
continue;
if( component.GetPrefabParent() == null ) // Component is added as override
return true;
if( ( !isRootTransform || !( component is Transform ) ) && component.HasAnyPrefabOverrides() ) // Component is modified (excluding root Transform)
return true;
}
int componentCount = components.Count;
components.Clear();
prefab.GetComponents( components );
if( components.Count != componentCount ) // Has some destroyed components as override
return true;
for( int i = 0, childCount = transform.childCount; i < childCount; i++ )
{
Transform child = transform.GetChild( i );
if( child != null )
stack.Push( child );
}
}
return false;
}
// Returns an enumerator to iterate through all asset paths in the folder
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
{
@@ -177,6 +272,12 @@ namespace AssetUsageDetectorNamespace
selection = objTR.gameObject;
#endif
}
else if( prefabAssetType == PrefabAssetType.Model )
{
objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
}
#else
Transform objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
@@ -190,6 +291,11 @@ namespace AssetUsageDetectorNamespace
// Can't ping assets that are hidden from Project window (e.g. animator states of AnimatorController), ping the main asset at that path instead
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
}
else if( !AssetDatabase.IsMainAsset( obj ) && Array.IndexOf( AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( obj ) ), obj ) < 0 )
{
// VFX Graph assets' nodes are serialized as part of the graph but they are invisible in the Project window even though their hideFlags is None (I don't know how)
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
}
}
}
@@ -405,9 +511,9 @@ namespace AssetUsageDetectorNamespace
// Check if all open scenes are saved (not dirty)
public static bool AreScenesSaved()
{
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
Scene scene = SceneManager.GetSceneAt( i );
if( scene.isDirty || string.IsNullOrEmpty( scene.path ) )
return false;
}
@@ -435,6 +541,15 @@ namespace AssetUsageDetectorNamespace
return stringBuilder.ToString();
}
// Draw header inside OnGUI
public static void DrawHeader( string label )
{
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( label, BoxGUIStyle, GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
}
// Draw horizontal line inside OnGUI
public static void DrawSeparatorLine()
{
@@ -460,7 +575,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < objectsToSearch.Count; i++ )
{
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) )
if( objectsToSearch[i].obj != null )
return false;
}
@@ -468,38 +583,20 @@ namespace AssetUsageDetectorNamespace
}
// Check if all the objects inside the list are null
public static bool IsEmpty( this List<Object> objects )
public static bool IsEmpty<T>( this List<T> objects ) where T : Object
{
if( objects == null )
return true;
for( int i = 0; i < objects.Count; i++ )
{
if( objects[i] != null && !objects[i].Equals( null ) )
if( objects[i] != null )
return false;
}
return true;
}
// Check if all the objects that are enumerated are null
public static bool IsEmpty( this IEnumerable<Object> objects )
{
if( objects == null )
return true;
using( IEnumerator<Object> enumerator = objects.GetEnumerator() )
{
while( enumerator.MoveNext() )
{
if( enumerator.Current != null && !enumerator.Current.Equals( null ) )
return false;
}
}
return true;
}
// Returns true is str starts with prefix
public static bool StartsWithFast( this string str, string prefix )
{
@@ -1,5 +1,6 @@
using System;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace AssetUsageDetectorNamespace
@@ -39,7 +40,12 @@ namespace AssetUsageDetectorNamespace
}
catch( Exception e )
{
Debug.LogException( e );
StringBuilder sb = Utilities.stringBuilder;
sb.Length = 0;
sb.Append( "Error while getting the value of (" ).Append( IsProperty ? ( (PropertyInfo) variable ).PropertyType : ( (FieldInfo) variable ).FieldType ).Append( ") " )
.Append( variable.DeclaringType ).Append( "." ).Append( Name ).Append( ": " ).Append( e );
Debug.LogError( sb.ToString() );
return null;
}
}
+3 -44
View File
@@ -1,45 +1,4 @@
= Asset Usage Detector =
= Asset Usage Detector (v2.5.5) =
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
### ABOUT
This tool helps you find usages of the selected asset(s) and/or scene object(s), i.e. lists the objects that refer to them.
### 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"
- Asset Usage Detector window can be locked via the "Lock" button in its context menu (or via the lock icon at the top-right corner). If all the
open windows are locked, "Search For References" opens a new window
- Seach results are split into different groups (scenes, assets, Project Settings) and each group displays its search results in its own tree view.
Tree views support multi-selection and keyboard navigation. It's possible to hide groups or rows via their context menu (right click)
- Each root row in a group's tree view represents a different searched object and is drawn with an outline. Usage(s) of a searched object are listed under it as
child rows (with indentation). If a child row's label contains bold text inside square brackets (e.g. "[Variable: m_Shader]"), then that text describes how
its parent row is connected to that row (i.e. the value assigned to the m_Shader variable of that row is its parent row). Child rows can have their own children
as some references involve multiple steps (e.g. when a Texture reference is found in a material which is used in a prefab which is referenced by a scene object)
- Rows with green tint to their left are the main references. For example, main references in a scene are the GameObjects that belong to that scene
- Rows with yellow tint are the parent rows of the selected row(s). To see a row's connection to the searched object, the yellow tinted rows can be traversed
from bottom to top (or, you can hover the cursor over a row and see its connection to the searched object in a tooltip)
- Rows with gradient blue tint are the other occurrences of the selected row(s) (a row can appear multiple times in the tree view, right clicking the row and
selecting "Expand All Occurrences" will reveal them all)
- When "Hide duplicate rows" option is enabled and a row's label starts with "[D]", then it means that the row has appeared in the tree view before and its children
were omitted to simplify the search results (because otherwise the same child rows would be displayed for each occurrence of that row). Only the first occurrence
of a row will display its children when "Hide duplicate rows" is enabled. To find a row's first occurrence, you can right click it and select "Select First Occurrence"
- Inside "Unused Objects" group, if a row's label starts with "[!]", then it means that some of its children are used in the project and it isn't safe to delete
that object. Right clicking the row and selecting "Show Used Children" will reveal the used children
- When a prefab's row is double clicked, that prefab is automatically opened in Prefab Mode
- Selections in tree views are completely independent from each other, it isn't possible to multi-select objects in different tree views. Likewise, selected rows in
a tree view won't be highlighted in other tree views. "Hide duplicate rows" also works independently for each tree view
- You can tweak most settings/colors via "Project Settings/yasirkula/Asset Usage Detector" page (on older versions, this menu is located at "Preferences" window)
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "2.2.0",
"version": "2.5.5",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",