Compare commits

..

12 Commits

14 changed files with 269 additions and 395 deletions
+2 -2
View File
@@ -21,8 +21,8 @@ There are 5 ways to install this plugin:
- import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package* - import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package*
- clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder - clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder
- import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837) - import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837)
- *(via Package Manager)* add the following line to *Packages/manifest.json*: - *(via Package Manager)* click the + button and install the package from the following git URL:
- `"com.yasirkula.assetusagedetector": "https://github.com/yasirkula/UnityAssetUsageDetector.git",` - `https://github.com/yasirkula/UnityAssetUsageDetector.git`
- *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command: - *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command:
- `openupm add com.yasirkula.assetusagedetector` - `openupm add com.yasirkula.assetusagedetector`
@@ -1,5 +1,3 @@
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
@@ -53,8 +51,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
public bool calculateUnusedObjects = false; public bool calculateUnusedObjects = false;
public bool hideDuplicateRows = true; public bool hideDuplicateRows = true;
public bool hideNonOverriddenPrefabVariablesInAssets = true; public bool hideRedundantPrefabReferencesInAssets = false;
public bool hideNonOverriddenPrefabVariablesInScenes = false; public bool hideRedundantPrefabReferencesInScenes = false;
public bool noAssetDatabaseChanges = false; public bool noAssetDatabaseChanges = false;
public bool showDetailedProgressBar = true; public bool showDetailedProgressBar = true;
} }
@@ -93,13 +91,9 @@ namespace AssetUsageDetectorNamespace
private bool searchingSourceAssets; private bool searchingSourceAssets;
private bool isInPlayMode; private bool isInPlayMode;
#if UNITY_2018_3_OR_NEWER
private PrefabStage openPrefabStage; private PrefabStage openPrefabStage;
private GameObject openPrefabStagePrefabAsset; private GameObject openPrefabStagePrefabAsset;
#if UNITY_2020_1_OR_NEWER
private GameObject openPrefabStageContextObject; private GameObject openPrefabStageContextObject;
#endif
#endif
private int searchedObjectsCount; // Number of searched objects private int searchedObjectsCount; // Number of searched objects
private double searchStartTime; private double searchStartTime;
@@ -121,7 +115,6 @@ namespace AssetUsageDetectorNamespace
return new SearchResult( false, null, null, null, this, searchParameters ); return new SearchResult( false, null, null, null, this, searchParameters );
} }
#if UNITY_2018_3_OR_NEWER
openPrefabStagePrefabAsset = null; openPrefabStagePrefabAsset = null;
string openPrefabStageAssetPath = null; string openPrefabStageAssetPath = null;
openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
@@ -138,20 +131,12 @@ namespace AssetUsageDetectorNamespace
return new SearchResult( false, null, null, null, this, searchParameters ); return new SearchResult( false, null, null, null, this, searchParameters );
} }
#if UNITY_2020_1_OR_NEWER
string prefabAssetPath = openPrefabStage.assetPath; string prefabAssetPath = openPrefabStage.assetPath;
#else
string prefabAssetPath = openPrefabStage.prefabAssetPath;
#endif
openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabAssetPath ); openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabAssetPath );
openPrefabStageAssetPath = prefabAssetPath; openPrefabStageAssetPath = prefabAssetPath;
#if UNITY_2020_1_OR_NEWER
openPrefabStageContextObject = openPrefabStage.openedFromInstanceRoot; openPrefabStageContextObject = openPrefabStage.openedFromInstanceRoot;
#endif
} }
} }
#endif
List<SearchResultGroup> searchResult = null; List<SearchResultGroup> searchResult = null;
isInPlayMode = EditorApplication.isPlaying; isInPlayMode = EditorApplication.isPlaying;
@@ -193,9 +178,7 @@ namespace AssetUsageDetectorNamespace
excludedAssetsPathsSet.Clear(); excludedAssetsPathsSet.Clear();
alwaysSearchedExtensionsSet.Clear(); alwaysSearchedExtensionsSet.Clear();
shaderIncludesToSearchSet.Clear(); shaderIncludesToSearchSet.Clear();
#if UNITY_2017_3_OR_NEWER
assemblyDefinitionFilesToSearch.Clear(); assemblyDefinitionFilesToSearch.Clear();
#endif
if( assetDependencyCache == null ) if( assetDependencyCache == null )
{ {
@@ -454,7 +437,7 @@ namespace AssetUsageDetectorNamespace
} }
// If a reference is found in the Project view, save the results // If a reference is found in the Project view, save the results
if( currentSearchResultGroup.NumberOfReferences > 0 ) if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
} }
@@ -479,7 +462,7 @@ namespace AssetUsageDetectorNamespace
} }
} }
if( currentSearchResultGroup.NumberOfReferences > 0 ) if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
} }
@@ -527,7 +510,6 @@ namespace AssetUsageDetectorNamespace
if( excludedScenesPathsSet.Contains( scenePath ) ) if( excludedScenesPathsSet.Contains( scenePath ) )
continue; continue;
#if UNITY_2019_2_OR_NEWER
// Skip scenes in read-only packages (Issue #36) // Skip scenes in read-only packages (Issue #36)
// Credit: https://forum.unity.com/threads/check-if-asset-inside-package-is-readonly.900902/#post-5990822 // Credit: https://forum.unity.com/threads/check-if-asset-inside-package-is-readonly.900902/#post-5990822
if( !scenePath.StartsWithFast( "Assets/" ) ) if( !scenePath.StartsWithFast( "Assets/" ) )
@@ -536,7 +518,6 @@ namespace AssetUsageDetectorNamespace
if( packageInfo != null && packageInfo.source != UnityEditor.PackageManager.PackageSource.Embedded && packageInfo.source != UnityEditor.PackageManager.PackageSource.Local ) if( packageInfo != null && packageInfo.source != UnityEditor.PackageManager.PackageSource.Embedded && packageInfo.source != UnityEditor.PackageManager.PackageSource.Local )
continue; continue;
} }
#endif
SearchScene( scenePath, searchResult, searchParameters, initialSceneSetup ); SearchScene( scenePath, searchResult, searchParameters, initialSceneSetup );
} }
@@ -554,7 +535,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < rootGameObjects.Length; i++ ) for( int i = 0; i < rootGameObjects.Length; i++ )
SearchGameObjectRecursively( rootGameObjects[i] ); SearchGameObjectRecursively( rootGameObjects[i] );
if( currentSearchResultGroup.NumberOfReferences > 0 ) if( currentSearchResultGroup.AnyReferencesFound )
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
} }
@@ -625,11 +606,9 @@ namespace AssetUsageDetectorNamespace
if( EditorSceneManager.GetActiveScene() != activeScene ) if( EditorSceneManager.GetActiveScene() != activeScene )
EditorSceneManager.SetActiveScene( 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 a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed
if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) ) if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) )
{ {
#if UNITY_2020_1_OR_NEWER
bool shouldOpenPrefabStageWithoutContext = true; bool shouldOpenPrefabStageWithoutContext = true;
if( openPrefabStageContextObject != null && !openPrefabStageContextObject.Equals( null ) ) if( openPrefabStageContextObject != null && !openPrefabStageContextObject.Equals( null ) )
{ {
@@ -647,12 +626,8 @@ namespace AssetUsageDetectorNamespace
} }
if( shouldOpenPrefabStageWithoutContext ) if( shouldOpenPrefabStageWithoutContext )
#endif
{
AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) ); AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) );
}
} }
#endif
} }
} }
@@ -663,7 +638,7 @@ namespace AssetUsageDetectorNamespace
searchResult[i].InitializeNodes( objectsToSearchSet ); searchResult[i].InitializeNodes( objectsToSearchSet );
// Remove empty search result groups // Remove empty search result groups
if( !searchResult[i].PendingSearch && searchResult[i].NumberOfReferences == 0 ) if( !searchResult[i].PendingSearch && !searchResult[i].AnyReferencesFound )
searchResult.RemoveAt( i-- ); searchResult.RemoveAt( i-- );
} }
} }
@@ -837,7 +812,6 @@ namespace AssetUsageDetectorNamespace
objectsToSearchSet.Add( obj ); objectsToSearchSet.Add( obj );
#if UNITY_2018_3_OR_NEWER
// When searching for references of a prefab stage object, try adding its corresponding prefab asset to the searched assets, as well // When searching for references of a prefab stage object, try adding its corresponding prefab asset to the searched assets, as well
if( openPrefabStage != null && openPrefabStagePrefabAsset != null && obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) obj ) ) if( openPrefabStage != null && openPrefabStagePrefabAsset != null && obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{ {
@@ -845,7 +819,6 @@ namespace AssetUsageDetectorNamespace
if( prefabStageObjectSource != null ) if( prefabStageObjectSource != null )
AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects ); AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects );
} }
#endif
bool isAsset = obj.IsAsset(); bool isAsset = obj.IsAsset();
if( isAsset ) if( isAsset )
@@ -982,11 +955,9 @@ namespace AssetUsageDetectorNamespace
EditorSceneManager.CloseScene( scene, true ); EditorSceneManager.CloseScene( scene, true );
} }
} }
else
{ if( currentSearchResultGroup.AnyReferencesFound )
// Some references are found in this scene, save the results
searchResult.Add( currentSearchResultGroup ); searchResult.Add( currentSearchResultGroup );
}
} }
// Search a GameObject and its children for references recursively // Search a GameObject and its children for references recursively
@@ -8,19 +8,11 @@ using UnityEditor;
using UnityEditor.Animations; using UnityEditor.Animations;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
#if UNITY_2017_1_OR_NEWER
using UnityEngine.U2D; using UnityEngine.U2D;
using UnityEngine.Playables; using UnityEngine.Playables;
#endif
#if UNITY_2018_2_OR_NEWER
using UnityEditor.U2D; using UnityEditor.U2D;
#endif
#if UNITY_2017_3_OR_NEWER
using UnityEditor.Compilation; using UnityEditor.Compilation;
#endif
#if UNITY_2017_2_OR_NEWER
using UnityEngine.Tilemaps; using UnityEngine.Tilemaps;
#endif
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets;
#endif #endif
@@ -31,19 +23,13 @@ namespace AssetUsageDetectorNamespace
public partial class AssetUsageDetector public partial class AssetUsageDetector
{ {
#region Helper Classes #region Helper Classes
#if UNITY_2017_3_OR_NEWER
#pragma warning disable 0649 // The fields' values are assigned via JsonUtility
[Serializable] [Serializable]
private struct AssemblyDefinitionReferences private struct AssemblyDefinitionReferences
{ {
public string reference; // Used by AssemblyDefinitionReferenceAssets public string reference; // Used by AssemblyDefinitionReferenceAssets
public List<string> references; // Used by AssemblyDefinitionAssets public List<string> references; // Used by AssemblyDefinitionAssets
} }
#pragma warning restore 0649
#endif
#if UNITY_2018_1_OR_NEWER
#pragma warning disable 0649 // The fields' values are assigned via JsonUtility
[Serializable] [Serializable]
private struct ShaderGraphReferences // Used by old Shader Graph serialization format private struct ShaderGraphReferences // Used by old Shader Graph serialization format
{ {
@@ -156,8 +142,6 @@ namespace AssetUsageDetectorNamespace
return null; return null;
} }
} }
#pragma warning restore 0649
#endif
#endregion #endregion
// Dictionary to quickly find the function to search a specific type with // Dictionary to quickly find the function to search a specific type with
@@ -176,10 +160,8 @@ namespace AssetUsageDetectorNamespace
// Path(s) of .cginc, .cg, .hlsl and .glslinc assets in assetsToSearchSet // Path(s) of .cginc, .cg, .hlsl and .glslinc assets in assetsToSearchSet
private readonly HashSet<string> shaderIncludesToSearchSet = new HashSet<string>(); private readonly HashSet<string> shaderIncludesToSearchSet = new HashSet<string>();
#if UNITY_2017_3_OR_NEWER
// Path(s) of the Assembly Definition Files in objectsToSearchSet (Value: files themselves) // Path(s) of the Assembly Definition Files in objectsToSearchSet (Value: files themselves)
private readonly Dictionary<string, Object> assemblyDefinitionFilesToSearch = new Dictionary<string, Object>( 8 ); private readonly Dictionary<string, Object> assemblyDefinitionFilesToSearch = new Dictionary<string, Object>( 8 );
#endif
// An optimization to fetch an animation clip's curve bindings only once // An optimization to fetch an animation clip's curve bindings only once
private readonly Dictionary<AnimationClip, EditorCurveBinding[]> animationClipUniqueBindings = new Dictionary<AnimationClip, EditorCurveBinding[]>( 256 ); private readonly Dictionary<AnimationClip, EditorCurveBinding[]> animationClipUniqueBindings = new Dictionary<AnimationClip, EditorCurveBinding[]>( 256 );
@@ -187,10 +169,7 @@ namespace AssetUsageDetectorNamespace
private bool searchPrefabConnections; private bool searchPrefabConnections;
private bool searchMonoBehavioursForScript; private bool searchMonoBehavioursForScript;
private bool searchTextureReferences; private bool searchTextureReferences;
#if UNITY_2018_1_OR_NEWER
private bool searchShaderGraphsForSubGraphs; private bool searchShaderGraphsForSubGraphs;
#endif
private bool searchSerializableVariablesOnly; private bool searchSerializableVariablesOnly;
private bool prevSearchSerializableVariablesOnly; private bool prevSearchSerializableVariablesOnly;
@@ -199,20 +178,15 @@ namespace AssetUsageDetectorNamespace
// Unity's internal function that returns a SerializedProperty's corresponding FieldInfo // Unity's internal function that returns a SerializedProperty's corresponding FieldInfo
private delegate FieldInfo FieldInfoGetter( SerializedProperty p, out Type t ); private delegate FieldInfo FieldInfoGetter( SerializedProperty p, out Type t );
#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 ) ); 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> 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 ) ); 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 #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 ) ); 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 #endif
internal static readonly Func<SpriteAtlas, Sprite[]> spriteAtlasPackedSpritesGetter = (Func<SpriteAtlas, Sprite[]>) Delegate.CreateDelegate( typeof( Func<SpriteAtlas, Sprite[]> ), typeof( SpriteAtlasExtensions ).GetMethod( "GetPackedSprites", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
#if ASSET_USAGE_ADDRESSABLES #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 ); private readonly PropertyInfo assetReferenceSubObjectTypeGetter = typeof( AssetReference ).GetProperty( "SubOjbectType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance );
#endif #endif
@@ -244,9 +218,7 @@ namespace AssetUsageDetectorNamespace
{ typeof( TerrainData ), SearchTerrainData }, { typeof( TerrainData ), SearchTerrainData },
{ typeof( LightmapSettings ), SearchLightmapSettings }, { typeof( LightmapSettings ), SearchLightmapSettings },
{ typeof( RenderSettings ), SearchRenderSettings }, { typeof( RenderSettings ), SearchRenderSettings },
#if UNITY_2017_1_OR_NEWER
{ typeof( SpriteAtlas ), SearchSpriteAtlas }, { typeof( SpriteAtlas ), SearchSpriteAtlas },
#endif
}; };
} }
@@ -259,16 +231,10 @@ namespace AssetUsageDetectorNamespace
{ "cg", SearchShaderSecondaryAsset }, { "cg", SearchShaderSecondaryAsset },
{ "glslinc", SearchShaderSecondaryAsset }, { "glslinc", SearchShaderSecondaryAsset },
{ "hlsl", SearchShaderSecondaryAsset }, { "hlsl", SearchShaderSecondaryAsset },
#if UNITY_2017_3_OR_NEWER
{ "asmdef", SearchAssemblyDefinitionFile }, { "asmdef", SearchAssemblyDefinitionFile },
#endif
#if UNITY_2019_2_OR_NEWER
{ "asmref", SearchAssemblyDefinitionFile }, { "asmref", SearchAssemblyDefinitionFile },
#endif
#if UNITY_2018_1_OR_NEWER
{ "shadergraph", SearchShaderGraph }, { "shadergraph", SearchShaderGraph },
{ "shadersubgraph", SearchShaderGraph }, { "shadersubgraph", SearchShaderGraph },
#endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
{ "vfx", SearchVFXGraphAsset }, { "vfx", SearchVFXGraphAsset },
{ "vfxoperator", SearchVFXGraphAsset }, { "vfxoperator", SearchVFXGraphAsset },
@@ -291,9 +257,7 @@ namespace AssetUsageDetectorNamespace
searchPrefabConnections = false; searchPrefabConnections = false;
searchMonoBehavioursForScript = false; searchMonoBehavioursForScript = false;
searchTextureReferences = false; searchTextureReferences = false;
#if UNITY_2018_1_OR_NEWER
searchShaderGraphsForSubGraphs = false; searchShaderGraphsForSubGraphs = false;
#endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
bool searchVFXGraphs = false; bool searchVFXGraphs = false;
#endif #endif
@@ -315,10 +279,8 @@ namespace AssetUsageDetectorNamespace
} }
else if( obj is GameObject ) else if( obj is GameObject )
searchPrefabConnections = true; searchPrefabConnections = true;
#if UNITY_2017_3_OR_NEWER
else if( obj is UnityEditorInternal.AssemblyDefinitionAsset ) else if( obj is UnityEditorInternal.AssemblyDefinitionAsset )
assemblyDefinitionFilesToSearch[AssetDatabase.GetAssetPath( obj )] = obj; assemblyDefinitionFilesToSearch[AssetDatabase.GetAssetPath( obj )] = obj;
#endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
else if( !searchVFXGraphs && ( obj is Shader || obj is Mesh || obj.GetType().Name.StartsWithFast( "PointCache" ) || obj.GetType().Name == "ShaderGraphVfxAsset" ) ) else if( !searchVFXGraphs && ( obj is Shader || obj is Mesh || obj.GetType().Name.StartsWithFast( "PointCache" ) || obj.GetType().Name == "ShaderGraphVfxAsset" ) )
searchVFXGraphs = true; searchVFXGraphs = true;
@@ -337,10 +299,8 @@ namespace AssetUsageDetectorNamespace
string extension = Utilities.GetFileExtension( path ); string extension = Utilities.GetFileExtension( path );
if( extension == "hlsl" || extension == "cginc" || extension == "cg" || extension == "glslinc" ) if( extension == "hlsl" || extension == "cginc" || extension == "cg" || extension == "glslinc" )
shaderIncludesToSearchSet.Add( path ); shaderIncludesToSearchSet.Add( path );
#if UNITY_2018_1_OR_NEWER
else if( extension == "shadersubgraph" ) else if( extension == "shadersubgraph" )
searchShaderGraphsForSubGraphs = true; searchShaderGraphsForSubGraphs = true;
#endif
} }
// AssetDatabase.GetDependencies doesn't take #include lines in shader source codes into consideration. If we are searching for references // AssetDatabase.GetDependencies doesn't take #include lines in shader source codes into consideration. If we are searching for references
@@ -355,19 +315,14 @@ namespace AssetUsageDetectorNamespace
alwaysSearchedExtensionsSet.Add( "hlsl" ); alwaysSearchedExtensionsSet.Add( "hlsl" );
} }
#if UNITY_2017_3_OR_NEWER
// AssetDatabase.GetDependencies doesn't return references from Assembly Definition Files to their Assembly Definition References, // AssetDatabase.GetDependencies doesn't return references from Assembly Definition Files to their Assembly Definition References,
// so if we are searching for an Assembly Definition File's usages, we must search all Assembly Definition Files' references manually. // so if we are searching for an Assembly Definition File's usages, we must search all Assembly Definition Files' references manually.
if( assemblyDefinitionFilesToSearch.Count > 0 ) if( assemblyDefinitionFilesToSearch.Count > 0 )
{ {
alwaysSearchedExtensionsSet.Add( "asmdef" ); alwaysSearchedExtensionsSet.Add( "asmdef" );
#if UNITY_2019_2_OR_NEWER
alwaysSearchedExtensionsSet.Add( "asmref" ); alwaysSearchedExtensionsSet.Add( "asmref" );
#endif
} }
#endif
#if UNITY_2018_1_OR_NEWER
// AssetDatabase.GetDependencies doesn't work with Shader Graph assets. We must search all Shader Graph assets in the following cases: // AssetDatabase.GetDependencies doesn't work with Shader Graph assets. We must search all Shader Graph assets in the following cases:
// searchTextureReferences: to find Texture references used in various nodes and properties // searchTextureReferences: to find Texture references used in various nodes and properties
// searchShaderGraphsForSubGraphs: to find Shader Sub-graph references in other Shader Graph assets // searchShaderGraphsForSubGraphs: to find Shader Sub-graph references in other Shader Graph assets
@@ -377,7 +332,6 @@ namespace AssetUsageDetectorNamespace
alwaysSearchedExtensionsSet.Add( "shadergraph" ); alwaysSearchedExtensionsSet.Add( "shadergraph" );
alwaysSearchedExtensionsSet.Add( "shadersubgraph" ); alwaysSearchedExtensionsSet.Add( "shadersubgraph" );
} }
#endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
if( searchTextureReferences || searchVFXGraphs ) if( searchTextureReferences || searchVFXGraphs )
@@ -397,16 +351,21 @@ namespace AssetUsageDetectorNamespace
// Check if this GameObject's prefab is one of the selected assets // Check if this GameObject's prefab is one of the selected assets
if( searchPrefabConnections ) if( searchPrefabConnections )
{ {
#if UNITY_2018_3_OR_NEWER bool? skipFurtherPrefabReferences = null;
Object prefab = go; for( GameObject goPrefab = go.GetPrefabParent(), prefab = goPrefab; prefab != null; prefab = prefab.GetPrefabParent() )
while( prefab = PrefabUtility.GetCorrespondingObjectFromSource( prefab ) )
#else
Object prefab = PrefabUtility.GetPrefabParent( go );
if( prefab )
#endif
{ {
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" ); referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" );
if( searchParameters.searchRefactoring != null ) if( searchParameters.searchRefactoring != null )
@@ -440,10 +399,15 @@ namespace AssetUsageDetectorNamespace
MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component ); MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component );
if( objectsToSearchSet.Contains( script ) ) if( objectsToSearchSet.Contains( script ) )
{ {
referenceNode.AddLinkTo( GetReferenceNode( script ) ); if( ShouldExcludeRedundantPrefabReferences( component ) && !component.HasAnyPrefabOverrides() )
currentSearchResultGroup.NumberOfRedundantReferences++;
else
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( searchParameters.searchRefactoring != null ) if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( component.gameObject, script, component ) ); searchParameters.searchRefactoring( new BehaviourUsageMatch( component.gameObject, script, component ) );
}
} }
} }
@@ -492,7 +456,6 @@ namespace AssetUsageDetectorNamespace
// Search the objects that are animated by this Animator component for references // Search the objects that are animated by this Animator component for references
SearchAnimatedObjects( referenceNode ); SearchAnimatedObjects( referenceNode );
} }
#if UNITY_2017_2_OR_NEWER
else if( component is Tilemap ) else if( component is Tilemap )
{ {
// Search the tiles for references // Search the tiles for references
@@ -510,8 +473,6 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#endif
#if UNITY_2017_1_OR_NEWER
else if( component is PlayableDirector ) else if( component is PlayableDirector )
{ {
// Search the PlayableAsset's scene bindings for references // Search the PlayableAsset's scene bindings for references
@@ -528,7 +489,6 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#endif
else if( component is ParticleSystemRenderer ) else if( component is ParticleSystemRenderer )
{ {
// Search ParticleSystemRenderer's custom meshes for references (at runtime, they can't be searched with reflection, unfortunately) // Search ParticleSystemRenderer's custom meshes for references (at runtime, they can't be searched with reflection, unfortunately)
@@ -565,11 +525,7 @@ namespace AssetUsageDetectorNamespace
try try
{ {
ParticleSystem.CollisionModule collisionModule = particleSystem.collision; ParticleSystem.CollisionModule collisionModule = particleSystem.collision;
#if UNITY_2020_2_OR_NEWER
for( int i = 0, j = collisionModule.planeCount; i < j; i++ ) for( int i = 0, j = collisionModule.planeCount; i < j; i++ )
#else
for( int i = 0, j = collisionModule.maxPlaneCount; i < j; i++ )
#endif
{ {
Transform plane = collisionModule.GetPlane( i ); Transform plane = collisionModule.GetPlane( i );
referenceNode.AddLinkTo( SearchObject( plane ), "Collision Module: Plane" ); referenceNode.AddLinkTo( SearchObject( plane ), "Collision Module: Plane" );
@@ -583,11 +539,7 @@ namespace AssetUsageDetectorNamespace
try try
{ {
ParticleSystem.TriggerModule triggerModule = particleSystem.trigger; ParticleSystem.TriggerModule triggerModule = particleSystem.trigger;
#if UNITY_2020_2_OR_NEWER
for( int i = 0, j = triggerModule.colliderCount; i < j; i++ ) for( int i = 0, j = triggerModule.colliderCount; i < j; i++ )
#else
for( int i = 0, j = triggerModule.maxColliderCount; i < j; i++ )
#endif
{ {
Component collider = triggerModule.GetCollider( i ); Component collider = triggerModule.GetCollider( i );
referenceNode.AddLinkTo( SearchObject( collider ), "Trigger Module: Collider" ); referenceNode.AddLinkTo( SearchObject( collider ), "Trigger Module: Collider" );
@@ -598,7 +550,6 @@ namespace AssetUsageDetectorNamespace
} }
catch { } catch { }
#if UNITY_2017_1_OR_NEWER
try try
{ {
ParticleSystem.TextureSheetAnimationModule textureSheetAnimationModule = particleSystem.textureSheetAnimation; ParticleSystem.TextureSheetAnimationModule textureSheetAnimationModule = particleSystem.textureSheetAnimation;
@@ -612,9 +563,7 @@ namespace AssetUsageDetectorNamespace
} }
} }
catch { } catch { }
#endif
#if UNITY_5_5_OR_NEWER
try try
{ {
ParticleSystem.SubEmittersModule subEmittersModule = particleSystem.subEmitters; ParticleSystem.SubEmittersModule subEmittersModule = particleSystem.subEmitters;
@@ -628,7 +577,6 @@ namespace AssetUsageDetectorNamespace
} }
} }
catch { } catch { }
#endif
} }
} }
@@ -732,10 +680,8 @@ namespace AssetUsageDetectorNamespace
{ {
string propertyName = ShaderUtil.GetPropertyName( shader, i ); string propertyName = ShaderUtil.GetPropertyName( shader, i );
Texture defaultTexture = shaderImporter.GetDefaultTexture( propertyName ); Texture defaultTexture = shaderImporter.GetDefaultTexture( propertyName );
#if UNITY_2018_1_OR_NEWER
if( !defaultTexture ) if( !defaultTexture )
defaultTexture = shaderImporter.GetNonModifiableTexture( propertyName ); defaultTexture = shaderImporter.GetNonModifiableTexture( propertyName );
#endif
if( objectsToSearchSet.Contains( defaultTexture ) ) if( objectsToSearchSet.Contains( defaultTexture ) )
{ {
@@ -1046,7 +992,6 @@ namespace AssetUsageDetectorNamespace
return referenceNode; return referenceNode;
} }
#if UNITY_2017_1_OR_NEWER
private ReferenceNode SearchSpriteAtlas( object obj ) private ReferenceNode SearchSpriteAtlas( object obj )
{ {
SpriteAtlas spriteAtlas = (SpriteAtlas) obj; SpriteAtlas spriteAtlas = (SpriteAtlas) obj;
@@ -1079,7 +1024,6 @@ namespace AssetUsageDetectorNamespace
searchParameters.searchRefactoring( new SerializedPropertyMatch( spriteAtlas, packedSprite, packedSpriteProperty ) ); searchParameters.searchRefactoring( new SerializedPropertyMatch( spriteAtlas, packedSprite, packedSpriteProperty ) );
} }
} }
#if UNITY_2018_2_OR_NEWER
else else
{ {
Object[] _packables = spriteAtlas.GetPackables(); Object[] _packables = spriteAtlas.GetPackables();
@@ -1089,7 +1033,6 @@ namespace AssetUsageDetectorNamespace
SearchSpriteAtlas( referenceNode, _packables[i] ); SearchSpriteAtlas( referenceNode, _packables[i] );
} }
} }
#endif
return referenceNode; return referenceNode;
} }
@@ -1135,9 +1078,7 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#endif
#if UNITY_2017_3_OR_NEWER
// Find references from an Assembly Definition File to its Assembly Definition References // Find references from an Assembly Definition File to its Assembly Definition References
private ReferenceNode SearchAssemblyDefinitionFile( object obj ) private ReferenceNode SearchAssemblyDefinitionFile( object obj )
{ {
@@ -1159,11 +1100,7 @@ namespace AssetUsageDetectorNamespace
{ {
for( int i = 0; i < assemblyDefinitionFile.references.Count; i++ ) for( int i = 0; i < assemblyDefinitionFile.references.Count; i++ )
{ {
#if UNITY_2019_1_OR_NEWER
string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference( assemblyDefinitionFile.references[i] ); string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference( assemblyDefinitionFile.references[i] );
#else
string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName( assemblyDefinitionFile.references[i] );
#endif
if( !string.IsNullOrEmpty( assemblyPath ) ) if( !string.IsNullOrEmpty( assemblyPath ) )
{ {
Object searchedAssemblyDefinitionFile; Object searchedAssemblyDefinitionFile;
@@ -1175,9 +1112,7 @@ namespace AssetUsageDetectorNamespace
return referenceNode; return referenceNode;
} }
#endif
#if UNITY_2018_1_OR_NEWER
// Searches Shader Graph assets for references // Searches Shader Graph assets for references
private ReferenceNode SearchShaderGraph( object obj ) private ReferenceNode SearchShaderGraph( object obj )
{ {
@@ -1306,7 +1241,6 @@ namespace AssetUsageDetectorNamespace
return referenceNode; return referenceNode;
} }
#endif
#if ASSET_USAGE_VFX_GRAPH #if ASSET_USAGE_VFX_GRAPH
private ReferenceNode SearchVFXGraphAsset( object obj ) private ReferenceNode SearchVFXGraphAsset( object obj )
@@ -1452,9 +1386,7 @@ namespace AssetUsageDetectorNamespace
if( iterator.Next( true ) ) if( iterator.Next( true ) )
{ {
bool iteratingVisible = iteratorVisible.NextVisible( true ); bool iteratingVisible = iteratorVisible.NextVisible( true );
#if UNITY_2018_3_OR_NEWER bool searchPrefabOverridesOnly = ShouldExcludeRedundantPrefabReferences( unityObject );
bool searchPrefabOverridesOnly = ( ( searchParameters.hideNonOverriddenPrefabVariablesInAssets && unityObject.IsAsset() ) || ( searchParameters.hideNonOverriddenPrefabVariablesInScenes && !unityObject.IsAsset() ) ) && PrefabUtility.GetCorrespondingObjectFromSource( unityObject ) != null;
#endif
bool enterChildren; bool enterChildren;
do do
{ {
@@ -1471,10 +1403,6 @@ namespace AssetUsageDetectorNamespace
if( !isVisible ) if( !isVisible )
enterChildren = false; enterChildren = false;
#if UNITY_2018_3_OR_NEWER
else if( searchPrefabOverridesOnly && !iterator.prefabOverride )
enterChildren = false;
#endif
else else
{ {
Object propertyValue; Object propertyValue;
@@ -1491,15 +1419,14 @@ namespace AssetUsageDetectorNamespace
searchResult = SearchObject( PreferablyGameObject( propertyValue ) ); searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false; enterChildren = false;
break; break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference: case SerializedPropertyType.ManagedReference:
object managedReferenceValue = GetRawSerializedPropertyValue( iterator ); object managedReferenceValue = GetRawSerializedPropertyValue( iterator );
propertyValue = managedReferenceValue as Object; propertyValue = managedReferenceValue as Object;
searchResult = SearchObject( PreferablyGameObject( managedReferenceValue ) ); searchResult = SearchObject( PreferablyGameObject( managedReferenceValue ) );
enterChildren = false; enterChildren = false;
break; break;
#endif
case SerializedPropertyType.Generic: case SerializedPropertyType.Generic:
{
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport && iterator.type.StartsWithFast( "AssetReference" ) && GetRawSerializedPropertyValue( iterator ) is AssetReference assetReference ) if( searchParameters.addressablesSupport && iterator.type.StartsWithFast( "AssetReference" ) && GetRawSerializedPropertyValue( iterator ) is AssetReference assetReference )
{ {
@@ -1526,6 +1453,7 @@ namespace AssetUsageDetectorNamespace
} }
break; break;
}
default: default:
propertyValue = null; propertyValue = null;
searchResult = null; searchResult = null;
@@ -1540,10 +1468,18 @@ namespace AssetUsageDetectorNamespace
// m_RD.texture is a redundant reference that shows up when searching sprites // m_RD.texture is a redundant reference that shows up when searching sprites
if( !propertyPath.EndsWithFast( "m_RD.texture" ) ) if( !propertyPath.EndsWithFast( "m_RD.texture" ) )
{ {
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath.Replace( ".Array.data[", "[" ) ); // "arrayVariable.Array.data[0]" becomes "arrayVariable[0]" 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 ) ) if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( unityObject, propertyValue, iterator ) ); searchParameters.searchRefactoring( new SerializedPropertyMatch( unityObject, propertyValue, iterator ) );
}
} }
} }
} }
@@ -1762,11 +1698,6 @@ namespace AssetUsageDetectorNamespace
// Same as above // Same as above
else if( ( propertyName == "material" || propertyName == "materials" ) && else if( ( propertyName == "material" || propertyName == "materials" ) &&
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) || ( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) ||
#if !UNITY_2019_3_OR_NEWER
#pragma warning disable 0618
typeof( GUIText ).IsAssignableFrom( currType ) ||
#pragma warning restore 0618
#endif
typeof( Collider2D ).IsAssignableFrom( currType ) ) ) typeof( Collider2D ).IsAssignableFrom( currType ) ) )
continue; continue;
// Ignore certain Material properties that are already searched via SearchMaterial function (also, if a material doesn't have a _Color or _BaseColor // Ignore certain Material properties that are already searched via SearchMaterial function (also, if a material doesn't have a _Color or _BaseColor
@@ -1922,6 +1853,11 @@ namespace AssetUsageDetectorNamespace
} }
#endif #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 // Iterates over all occurrences of specific key-value pairs in string
// Example1: #include "VALUE" valuePrefix=#include, valueWrapperChar=" // Example1: #include "VALUE" valuePrefix=#include, valueWrapperChar="
// Example2: "guid": "VALUE" valuePrefix="guid", valueWrapperChar=" // Example2: "guid": "VALUE" valuePrefix="guid", valueWrapperChar="
@@ -167,7 +167,6 @@ namespace AssetUsageDetectorNamespace
} }
#endregion #endregion
#if UNITY_2018_3_OR_NEWER
[SettingsProvider] [SettingsProvider]
public static SettingsProvider CreatePreferencesGUI() public static SettingsProvider CreatePreferencesGUI()
{ {
@@ -177,19 +176,11 @@ namespace AssetUsageDetectorNamespace
keywords = new System.Collections.Generic.HashSet<string>() { "Asset", "Usage", "Detector" } keywords = new System.Collections.Generic.HashSet<string>() { "Asset", "Usage", "Detector" }
}; };
} }
#endif
#if !UNITY_2018_3_OR_NEWER
[PreferenceItem( "Asset Usage Detector" )]
#endif
public static void PreferencesGUI() public static void PreferencesGUI()
{ {
float labelWidth = EditorGUIUtility.labelWidth; float labelWidth = EditorGUIUtility.labelWidth;
#if UNITY_2018_3_OR_NEWER
EditorGUIUtility.labelWidth += 60f; EditorGUIUtility.labelWidth += 60f;
#else
EditorGUIUtility.labelWidth += 20f;
#endif
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
@@ -1,5 +1,3 @@
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using System.Collections.Generic; using System.Collections.Generic;
@@ -32,11 +30,13 @@ namespace AssetUsageDetectorNamespace
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables"; private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps"; private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch"; private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
#if ASSET_USAGE_ADDRESSABLES
private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport"; private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
#endif
private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs"; private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates"; private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
private const string PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_ASSETS = "AUD_HideRedundantPVariantLinks"; private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS = "AUD_HideRedundantPRefsInAssets";
private const string PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_SCENES = "AUD_HideRedundantPVarsInScenes"; private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES = "AUD_HideRedundantPRefsInScenes";
private const string PREFS_SHOW_PROGRESS = "AUD_Progress"; private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" ); private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
@@ -44,6 +44,16 @@ namespace AssetUsageDetectorNamespace
private static 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; private GUIStyle lockButtonStyle;
private readonly AssetUsageDetector core = new AssetUsageDetector(); private readonly AssetUsageDetector core = new AssetUsageDetector();
@@ -52,7 +62,6 @@ namespace AssetUsageDetectorNamespace
// This isn't readonly so that it can be serialized // This isn't readonly so that it can be serialized
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) }; private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
#pragma warning disable 0649
[SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked [SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked
private bool m_isLocked; private bool m_isLocked;
private bool IsLocked private bool IsLocked
@@ -67,7 +76,6 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#pragma warning restore 0649
private Phase currentPhase = Phase.Setup; private Phase currentPhase = Phase.Setup;
@@ -94,8 +102,8 @@ namespace AssetUsageDetectorNamespace
private bool searchUnusedMaterialProperties = true; private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false; private bool calculateUnusedObjects = false;
private bool hideDuplicateRows = true; private bool hideDuplicateRows = true;
private bool hideNonOverriddenPrefabVariablesInAssets = true; private bool hideRedundantPrefabReferencesInAssets = false;
private bool hideNonOverriddenPrefabVariablesInScenes = false; private bool hideRedundantPrefabReferencesInScenes = false;
private bool noAssetDatabaseChanges = false; private bool noAssetDatabaseChanges = false;
private bool showDetailedProgressBar = true; private bool showDetailedProgressBar = true;
@@ -119,37 +127,7 @@ namespace AssetUsageDetectorNamespace
{ {
contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked ); contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked );
contextMenu.AddSeparator( "" ); contextMenu.AddSeparator( "" );
#if UNITY_2018_3_OR_NEWER
contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) ); contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) );
#else
contextMenu.AddItem( new GUIContent( "Settings" ), false, () =>
{
System.Type preferencesWindowType = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.PreferencesWindow" );
preferencesWindowType.GetMethod( "ShowPreferencesWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).Invoke( null, null );
EditorWindow preferencesWindow = GetWindow( preferencesWindowType );
if( (bool) preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow ) )
{
preferencesWindowType.GetMethod( "AddCustomSections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( preferencesWindow, null );
preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, false );
}
int targetSectionIndex = -1;
System.Collections.IList sections = (System.Collections.IList) preferencesWindowType.GetField( "m_Sections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow );
for( int i = 0; i < sections.Count; i++ )
{
if( ( (GUIContent) sections[i].GetType().GetField( "content", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( sections[i] ) ).text == "Asset Usage Detector" )
{
targetSectionIndex = i;
break;
}
}
if( targetSectionIndex >= 0 )
preferencesWindowType.GetProperty( "selectedSectionIndex", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, targetSectionIndex, null );
} );
#endif
if( currentPhase == Phase.Setup ) if( currentPhase == Phase.Setup )
{ {
@@ -333,8 +311,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
calculateUnusedObjects = searchParameters.calculateUnusedObjects; calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows; hideDuplicateRows = searchParameters.hideDuplicateRows;
hideNonOverriddenPrefabVariablesInAssets = searchParameters.hideNonOverriddenPrefabVariablesInAssets; hideRedundantPrefabReferencesInAssets = searchParameters.hideRedundantPrefabReferencesInAssets;
hideNonOverriddenPrefabVariablesInScenes = searchParameters.hideNonOverriddenPrefabVariablesInScenes; hideRedundantPrefabReferencesInScenes = searchParameters.hideRedundantPrefabReferencesInScenes;
noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges; noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
showDetailedProgressBar = searchParameters.showDetailedProgressBar; showDetailedProgressBar = searchParameters.showDetailedProgressBar;
@@ -374,17 +352,12 @@ namespace AssetUsageDetectorNamespace
if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip ) if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip )
wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1 wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets; PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
#endif
} }
private void OnDisable() private void OnDisable()
{ {
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets; PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
#endif
SearchResultTooltip.Hide(); SearchResultTooltip.Hide();
} }
@@ -417,8 +390,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects ); EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows ); EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
EditorPrefs.SetBool( PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_ASSETS, hideNonOverriddenPrefabVariablesInAssets ); EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
EditorPrefs.SetBool( PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_SCENES, hideNonOverriddenPrefabVariablesInScenes ); EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar ); EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
} }
@@ -440,8 +413,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false ); calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true ); hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
hideNonOverriddenPrefabVariablesInAssets = EditorPrefs.GetBool( PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_ASSETS, true ); hideRedundantPrefabReferencesInAssets = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
hideNonOverriddenPrefabVariablesInScenes = EditorPrefs.GetBool( PREFS_HIDE_NON_OVERRIDDEN_PREFAB_VARIABLES_IN_SCENES, false ); hideRedundantPrefabReferencesInScenes = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true ); showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
} }
@@ -502,24 +475,16 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10f ); GUILayout.Space( 10f );
Color c = GUI.backgroundColor; Utilities.DrawHeader( "<b>SEARCH IN</b>" );
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCH IN</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder ); searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
if( searchInAssetsFolder ) if( searchInAssetsFolder )
{ {
GUILayout.BeginHorizontal(); BeginIndentedGUI();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset ); searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
excludedAssetsDrawer.Draw( excludedAssets ); excludedAssetsDrawer.Draw( excludedAssets );
EndIndentedGUI();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
} }
GUILayout.Space( 5f ); GUILayout.Space( 5f );
@@ -540,13 +505,10 @@ namespace AssetUsageDetectorNamespace
if( searchInScenesInBuild ) if( searchInScenesInBuild )
{ {
GUILayout.BeginHorizontal(); BeginIndentedGUI( false );
GUILayout.Space( 35f );
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
EndIndentedGUI( false );
GUILayout.EndHorizontal();
} }
GUI.enabled = true; GUI.enabled = true;
@@ -554,14 +516,9 @@ namespace AssetUsageDetectorNamespace
searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes ); searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes );
} }
GUILayout.BeginHorizontal(); BeginIndentedGUI();
GUILayout.Space( 35f );
GUILayout.BeginVertical();
excludedScenesDrawer.Draw( excludedScenes ); excludedScenesDrawer.Draw( excludedScenes );
EndIndentedGUI();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup( !searchInOpenScenes && !searchInScenesInBuild && !searchInAllScenes ); EditorGUI.BeginDisabledGroup( !searchInOpenScenes && !searchInScenesInBuild && !searchInAllScenes );
searchInSceneLightingSettings = WordWrappingToggleLeft( "Scene Lighting Settings (WARNING: This may change the active scene during search)", searchInSceneLightingSettings ); searchInSceneLightingSettings = WordWrappingToggleLeft( "Scene Lighting Settings (WARNING: This may change the active scene during search)", searchInSceneLightingSettings );
@@ -573,9 +530,7 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10f ); GUILayout.Space( 10f );
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor; Utilities.DrawHeader( "<b>SETTINGS</b>" );
GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
#if ASSET_USAGE_ADDRESSABLES #if ASSET_USAGE_ADDRESSABLES
EditorGUI.BeginDisabledGroup( addressablesSupport ); EditorGUI.BeginDisabledGroup( addressablesSupport );
@@ -587,10 +542,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects ); calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows ); hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
#if UNITY_2018_3_OR_NEWER hideRedundantPrefabReferencesInAssets = WordWrappingToggleLeft( hideRedundantPrefabReferencesInAssetsLabel, hideRedundantPrefabReferencesInAssets );
hideNonOverriddenPrefabVariablesInAssets = WordWrappingToggleLeft( "Hide non-overridden prefab variables in assets (references found in non-overridden variables of prefab variants/nested prefabs will be hidden)", hideNonOverriddenPrefabVariablesInAssets ); hideRedundantPrefabReferencesInScenes = WordWrappingToggleLeft( hideRedundantPrefabReferencesInScenesLabel, hideRedundantPrefabReferencesInScenes );
hideNonOverriddenPrefabVariablesInScenes = WordWrappingToggleLeft( "Hide non-overridden prefab variables in scenes (references found in non-overridden variables of prefab instances will be hidden)", hideNonOverriddenPrefabVariablesInScenes );
#endif
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges ); 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 ); showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar );
@@ -664,10 +617,7 @@ namespace AssetUsageDetectorNamespace
private void DrawObjectsToSearchSection() private void DrawObjectsToSearchSection()
{ {
Color c = GUI.backgroundColor; Utilities.DrawHeader( "<b>SEARCHED OBJECTS</b>" );
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( "<b>SEARCHED OBJECTS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect(); Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect();
searchedObjectsHeaderRect.x += 5f; searchedObjectsHeaderRect.x += 5f;
@@ -680,7 +630,31 @@ namespace AssetUsageDetectorNamespace
objectsToSearchDrawer.Draw( objectsToSearch ); objectsToSearchDrawer.Draw( objectsToSearch );
} }
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 ) 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(); GUILayout.BeginHorizontal();
bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 ); bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 );
@@ -699,10 +673,7 @@ namespace AssetUsageDetectorNamespace
currentPhase = Phase.Processing; currentPhase = Phase.Processing;
SavePrefs(); SavePrefs();
#if UNITY_2018_3_OR_NEWER
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() ); ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
#endif
// Start searching // Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters() searchResult = core.Run( new AssetUsageDetector.Parameters()
@@ -730,8 +701,8 @@ namespace AssetUsageDetectorNamespace
#endif #endif
calculateUnusedObjects = calculateUnusedObjects, calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows, hideDuplicateRows = hideDuplicateRows,
hideNonOverriddenPrefabVariablesInAssets = hideNonOverriddenPrefabVariablesInAssets, hideRedundantPrefabReferencesInAssets = hideRedundantPrefabReferencesInAssets,
hideNonOverriddenPrefabVariablesInScenes = hideNonOverriddenPrefabVariablesInScenes, hideRedundantPrefabReferencesInScenes = hideRedundantPrefabReferencesInScenes && searchInAssetsFolder,
noAssetDatabaseChanges = noAssetDatabaseChanges, noAssetDatabaseChanges = noAssetDatabaseChanges,
showDetailedProgressBar = showDetailedProgressBar showDetailedProgressBar = showDetailedProgressBar
} ); } );
@@ -745,18 +716,13 @@ namespace AssetUsageDetectorNamespace
wantsMouseMove = wantsMouseEnterLeaveWindow = true; wantsMouseMove = wantsMouseEnterLeaveWindow = true;
} }
#if UNITY_2018_3_OR_NEWER
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets // Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage ) public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
{ {
if( prefabStage == null || !prefabStage.stageHandle.IsValid() ) if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
return; return;
#if UNITY_2020_1_OR_NEWER
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath ); GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
#else
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
#endif
if( prefabAsset == null || prefabAsset.Equals( null ) ) if( prefabAsset == null || prefabAsset.Equals( null ) )
return; return;
@@ -783,7 +749,6 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#endif
private bool ReturnToSetupPhase() private bool ReturnToSetupPhase()
{ {
@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.U2D;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace namespace AssetUsageDetectorNamespace
@@ -95,6 +96,20 @@ namespace AssetUsageDetectorNamespace
} }
} }
// Add Sprites of SpriteAtlases to the sub-assets list
if( target is SpriteAtlas spriteAtlas )
{
Sprite[] packedSprites = AssetUsageDetector.spriteAtlasPackedSpritesGetter( spriteAtlas );
if( packedSprites != null )
{
for( int i = 0; i < packedSprites.Length; i++ )
{
if( packedSprites[i] != null && currentSubAssets.Add( packedSprites[i] ) )
subAssets.Add( new SubAsset( packedSprites[i], shouldSearchChildren ?? true ) );
}
}
}
// Find sub-asset(s) of the asset (if any) // Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) ); Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ ) for( int i = 0; i < assets.Length; i++ )
@@ -103,13 +118,11 @@ namespace AssetUsageDetectorNamespace
if( asset == null || asset.Equals( null ) || asset is Component || asset == target ) if( asset == null || asset.Equals( null ) || asset is Component || asset == target )
continue; continue;
#if UNITY_2018_3_OR_NEWER
// Nested prefabs in prefab assets add an additional native object of type 'UnityEngine.PrefabInstance' to the prefab. Managed type of that native type // Nested prefabs in prefab assets add an additional native object of type 'UnityEngine.PrefabInstance' to the prefab. Managed type of that native type
// is UnityEngine.Object (i.e. GetType() returns UnityEngine.Object, not UnityEngine.PrefabInstance). There are no possible references to these native // is UnityEngine.Object (i.e. GetType() returns UnityEngine.Object, not UnityEngine.PrefabInstance). There are no possible references to these native
// objects so skip them (we're checking for UnityEngine.Prefab because it includes other native types like UnityEngine.PrefabCreation, as well) // objects so skip them (we're checking for UnityEngine.Prefab because it includes other native types like UnityEngine.PrefabCreation, as well)
if( target is GameObject && asset.GetType() == typeof( Object ) && asset.ToString().Contains( "(UnityEngine.Prefab" ) ) if( target is GameObject && asset.GetType() == typeof( Object ) && asset.ToString().Contains( "(UnityEngine.Prefab" ) )
continue; continue;
#endif
if( currentSubAssets.Add( asset ) ) if( currentSubAssets.Add( asset ) )
subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) ); subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) );
@@ -152,9 +152,7 @@ namespace AssetUsageDetectorNamespace
} }
break; break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference: SerializedProperty.managedReferenceValue = newValue; break; case SerializedPropertyType.ManagedReference: SerializedProperty.managedReferenceValue = newValue; break;
#endif
} }
SerializedProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo(); SerializedProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo();
@@ -288,10 +286,8 @@ namespace AssetUsageDetectorNamespace
List<string> textureNames = new List<string>( 16 ); List<string> textureNames = new List<string>( 16 );
List<Texture> textureValues = new List<Texture>( 16 ); List<Texture> textureValues = new List<Texture>( 16 );
#if UNITY_2018_1_OR_NEWER
List<string> nonModifiableTextureNames = new List<string>( 16 ); List<string> nonModifiableTextureNames = new List<string>( 16 );
List<Texture> nonModifiableTextureValues = new List<Texture>( 16 ); List<Texture> nonModifiableTextureValues = new List<Texture>( 16 );
#endif
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
for( int i = 0; i < shaderPropertyCount; i++ ) for( int i = 0; i < shaderPropertyCount; i++ )
@@ -300,7 +296,6 @@ namespace AssetUsageDetectorNamespace
continue; continue;
string propertyName = ShaderUtil.GetPropertyName( shader, i ); string propertyName = ShaderUtil.GetPropertyName( shader, i );
#if UNITY_2018_1_OR_NEWER
if( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) ) if( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) )
{ {
Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName ); Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName );
@@ -311,7 +306,6 @@ namespace AssetUsageDetectorNamespace
nonModifiableTextureValues.Add( propertyDefaultValue ); nonModifiableTextureValues.Add( propertyDefaultValue );
} }
else else
#endif
{ {
Texture propertyDefaultValue = shaderImporter.GetDefaultTexture( propertyName ); Texture propertyDefaultValue = shaderImporter.GetDefaultTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable ) if( propertyDefaultValue == Value && propertyName == Variable )
@@ -323,9 +317,7 @@ namespace AssetUsageDetectorNamespace
} }
shaderImporter.SetDefaultTextures( textureNames.ToArray(), textureValues.ToArray() ); shaderImporter.SetDefaultTextures( textureNames.ToArray(), textureValues.ToArray() );
#if UNITY_2018_1_OR_NEWER
shaderImporter.SetNonModifiableTextures( nonModifiableTextureNames.ToArray(), nonModifiableTextureValues.ToArray() ); shaderImporter.SetNonModifiableTextures( nonModifiableTextureNames.ToArray(), nonModifiableTextureValues.ToArray() );
#endif
AssetDatabase.ImportAsset( shaderImporter.assetPath ); AssetDatabase.ImportAsset( shaderImporter.assetPath );
} }
else else
@@ -23,6 +23,7 @@ namespace AssetUsageDetectorNamespace
public SearchResultGroup.GroupType type; public SearchResultGroup.GroupType type;
public bool isExpanded; public bool isExpanded;
public bool pendingSearch; public bool pendingSearch;
public int redundantReferences;
public SearchResultTreeViewState treeViewState; public SearchResultTreeViewState treeViewState;
public List<int> initialSerializedNodes; public List<int> initialSerializedNodes;
@@ -576,6 +577,9 @@ namespace AssetUsageDetectorNamespace
public int NumberOfReferences { get { return references.Count; } } public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } } public ReferenceNode this[int index] { get { return references[index]; } }
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 ) public SearchResultGroup( string title, GroupType type, bool isExpanded = true, bool pendingSearch = false )
{ {
Title = title.StartsWith( "<b>" ) ? title : string.Concat( "<b>", title, "</b>" ); Title = title.StartsWith( "<b>" ) ? title : string.Concat( "<b>", title, "</b>" );
@@ -816,6 +820,7 @@ namespace AssetUsageDetectorNamespace
removedRows.Add( treeViewRows[i].id ); removedRows.Add( treeViewRows[i].id );
} }
treeView.ClearSearch();
treeView.HideItems( removedRows ); treeView.HideItems( removedRows );
} ); } );
} }
@@ -868,6 +873,9 @@ namespace AssetUsageDetectorNamespace
if( IsExpanded ) 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 ) if( PendingSearch )
GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle ); GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
else if( references.Count == 0 ) else if( references.Count == 0 )
@@ -972,19 +980,8 @@ namespace AssetUsageDetectorNamespace
Rect treeViewRect = EditorGUILayout.GetControlRect( false, treeView.totalHeight ); Rect treeViewRect = EditorGUILayout.GetControlRect( false, treeView.totalHeight );
if( ev.type == EventType.Repaint ) if( ev.type == EventType.Repaint )
{
lastTreeViewRect = treeViewRect; lastTreeViewRect = treeViewRect;
#if !UNITY_2018_2_OR_NEWER
// TreeView calls RowGUI for all rows instead of only the visible rows on early Unity versions which leads to performance issues. Do manual row culling on those versions
// Credit: https://github.com/Unity-Technologies/UnityCsReference/blob/a048de916b23331bf6dfe92c4a6c205989b83b4f/Editor/Mono/GUI/TreeView/TreeViewGUI.cs#L273-L276
float topPixel = scrollPosition - treeViewRect.y;
float heightInPixels = window.position.height;
treeView.visibleRowTop = (int) Mathf.Floor( topPixel / treeView.rowHeight );
treeView.visibleRowBottom = treeView.visibleRowTop + (int) Mathf.Ceil( heightInPixels / treeView.rowHeight );
#endif
}
treeView.OnGUI( treeViewRect ); treeView.OnGUI( treeViewRect );
if( treeViewKeyboardNavigation && treeView.HasFocus() && treeView.HasSelection() ) if( treeViewKeyboardNavigation && treeView.HasFocus() && treeView.HasSelection() )
@@ -1064,6 +1061,7 @@ namespace AssetUsageDetectorNamespace
type = Type, type = Type,
isExpanded = IsExpanded, isExpanded = IsExpanded,
pendingSearch = PendingSearch, pendingSearch = PendingSearch,
redundantReferences = NumberOfRedundantReferences,
treeViewState = treeViewState treeViewState = treeViewState
}; };
@@ -1081,6 +1079,7 @@ namespace AssetUsageDetectorNamespace
// Deserialize this result group from the serialized data // Deserialize this result group from the serialized data
internal void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List<ReferenceNode> allNodes ) internal void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List<ReferenceNode> allNodes )
{ {
NumberOfRedundantReferences = serializedResultGroup.redundantReferences;
treeViewState = serializedResultGroup.treeViewState; treeViewState = serializedResultGroup.treeViewState;
if( serializedResultGroup.initialSerializedNodes != null ) if( serializedResultGroup.initialSerializedNodes != null )
@@ -26,11 +26,20 @@ namespace AssetUsageDetectorNamespace
public static void Show( Rect sourcePosition, string tooltip ) public static void Show( Rect sourcePosition, string tooltip )
{ {
// Don't lose focus to the previous window
EditorWindow prevFocusedWindow = focusedWindow;
if (!mainWindow)
{
mainWindow = CreateInstance<SearchResultTooltip>();
mainWindow.ShowPopup();
}
Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical ); Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical );
Rect preferredPosition; Rect preferredPosition;
Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize ); Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize );
Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect( positionLeft ); Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect(positionLeft, mainWindow);
Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position; Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position;
Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size; Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size;
@@ -39,7 +48,7 @@ namespace AssetUsageDetectorNamespace
else else
{ {
Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize ); Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize );
Rect screenFittedPositionRight = Utilities.GetScreenFittedRect( positionRight ); Rect screenFittedPositionRight = Utilities.GetScreenFittedRect(positionRight, mainWindow);
Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position; Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position;
Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size; Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size;
@@ -49,15 +58,6 @@ namespace AssetUsageDetectorNamespace
preferredPosition = screenFittedPositionLeft; preferredPosition = screenFittedPositionLeft;
} }
// Don't lose focus to the previous window
EditorWindow prevFocusedWindow = focusedWindow;
if( !mainWindow )
{
mainWindow = CreateInstance<SearchResultTooltip>();
mainWindow.ShowPopup();
}
SearchResultTooltip.tooltip = tooltip; SearchResultTooltip.tooltip = tooltip;
mainWindow.minSize = preferredPosition.size; mainWindow.minSize = preferredPosition.size;
mainWindow.position = preferredPosition; mainWindow.position = preferredPosition;
@@ -104,11 +104,7 @@ namespace AssetUsageDetectorNamespace
} }
private const float SEARCHED_OBJECTS_BORDER_THICKNESS = 1f; private const float SEARCHED_OBJECTS_BORDER_THICKNESS = 1f;
#if UNITY_2019_3_OR_NEWER private const float TREE_VIEW_LINES_THICKNESS = 1.5f; // There are inexplicable spaces between the vertical and horizontal lines if we set this to 2.0f on 2019.3+
private const float TREE_VIEW_LINES_THICKNESS = 1.5f; // There are inexplicable spaces between the vertical and horizontal lines if we don't change thickness by 0.5f on 2019.3+
#else
private const float TREE_VIEW_LINES_THICKNESS = 2f;
#endif
private const float HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS = TREE_VIEW_LINES_THICKNESS * 2f; private const float HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS = TREE_VIEW_LINES_THICKNESS * 2f;
private readonly new SearchResultTreeViewState state; private readonly new SearchResultTreeViewState state;
@@ -127,10 +123,6 @@ namespace AssetUsageDetectorNamespace
private bool isSearching; private bool isSearching;
#if !UNITY_2018_2_OR_NEWER
public int visibleRowTop = 0, visibleRowBottom = int.MaxValue;
#endif
private readonly CompareInfo textComparer = new CultureInfo( "en-US" ).CompareInfo; private readonly CompareInfo textComparer = new CultureInfo( "en-US" ).CompareInfo;
private readonly CompareOptions textCompareOptions = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace; private readonly CompareOptions textCompareOptions = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace;
@@ -150,13 +142,7 @@ namespace AssetUsageDetectorNamespace
public new float rowHeight public new float rowHeight
{ {
get { return base.rowHeight; } get { return base.rowHeight; }
set set { base.rowHeight = value; }
{
base.rowHeight = value;
#if !UNITY_2019_3_OR_NEWER
customFoldoutYOffset = ( value - EditorGUIUtility.singleLineHeight ) * 0.5f;
#endif
}
} }
// Avoid using these properties of TreeView by mistake // Avoid using these properties of TreeView by mistake
@@ -183,13 +169,7 @@ namespace AssetUsageDetectorNamespace
if( treeType != TreeType.IsolatedView ) if( treeType != TreeType.IsolatedView )
{ {
// Draw only the visible rows. This requires setting useScrollView to false because we are using an external scroll view: https://docs.unity3d.com/ScriptReference/IMGUI.Controls.TreeView-useScrollView.html // Draw only the visible rows. This requires setting useScrollView to false because we are using an external scroll view: https://docs.unity3d.com/ScriptReference/IMGUI.Controls.TreeView-useScrollView.html
#if UNITY_2018_2_OR_NEWER
useScrollView = false; useScrollView = false;
#else
// In my tests, SetUseScrollView seems to have no effect unfortunately but let's keep this line in case it fixes some other issues with the external scroll view
object treeViewController = typeof( TreeView ).GetField( "m_TreeView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( this );
treeViewController.GetType().GetMethod( "SetUseScrollView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( treeViewController, new object[1] { false } );
#endif
} }
isSearching = !string.IsNullOrEmpty( state.searchTerm ); isSearching = !string.IsNullOrEmpty( state.searchTerm );
@@ -200,6 +180,13 @@ namespace AssetUsageDetectorNamespace
RefreshSelectedNodes( GetSelection() ); RefreshSelectedNodes( GetSelection() );
} }
public void ClearSearch()
{
string prevSearchTerm = state.searchTerm;
state.searchTerm = "";
RefreshSearch( prevSearchTerm );
}
public void RefreshSearch( string prevSearchTerm ) public void RefreshSearch( string prevSearchTerm )
{ {
bool wasSearchTermEmpty = string.IsNullOrEmpty( prevSearchTerm ); bool wasSearchTermEmpty = string.IsNullOrEmpty( prevSearchTerm );
@@ -416,12 +403,6 @@ namespace AssetUsageDetectorNamespace
protected override void RowGUI( RowGUIArgs args ) protected override void RowGUI( RowGUIArgs args )
{ {
#if !UNITY_2018_2_OR_NEWER
// Do manual row culling on early Unity versions
if( args.row < visibleRowTop || args.row > visibleRowBottom )
return;
#endif
if( isTreeViewEmpty ) if( isTreeViewEmpty )
{ {
EditorGUI.LabelField( args.rowRect, "No matching results..." ); EditorGUI.LabelField( args.rowRect, "No matching results..." );
@@ -659,9 +640,6 @@ namespace AssetUsageDetectorNamespace
rect.xMin += GetContentIndent( args.item ); rect.xMin += GetContentIndent( args.item );
rect.y += AssetUsageDetectorSettings.ExtraRowHeight * 0.5f; rect.y += AssetUsageDetectorSettings.ExtraRowHeight * 0.5f;
#if !UNITY_2019_3_OR_NEWER
rect.y -= 2f;
#endif
rect.height += 4f; // Incrementing height fixes cropped icon issue on Unity 2019.2 or earlier rect.height += 4f; // Incrementing height fixes cropped icon issue on Unity 2019.2 or earlier
if( foldoutLabelStyle == null ) if( foldoutLabelStyle == null )
@@ -738,7 +716,6 @@ namespace AssetUsageDetectorNamespace
isLMBDown = false; isLMBDown = false;
Object clickedObject = GetDataFromId( id ).node.UnityObject; Object clickedObject = GetDataFromId( id ).node.UnityObject;
#if UNITY_2018_3_OR_NEWER
if( clickedObject && clickedObject.IsAsset() ) if( clickedObject && clickedObject.IsAsset() )
{ {
GameObject clickedPrefabRoot = null; GameObject clickedPrefabRoot = null;
@@ -755,16 +732,11 @@ namespace AssetUsageDetectorNamespace
// Try to open the prefab stage of this prefab // Try to open the prefab stage of this prefab
string assetPath = AssetDatabase.GetAssetPath( clickedPrefabRoot ); string assetPath = AssetDatabase.GetAssetPath( clickedPrefabRoot );
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
#if UNITY_2020_1_OR_NEWER
if( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath ) if( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath )
#else
if( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.prefabAssetPath )
#endif
AssetDatabase.OpenAsset( clickedPrefabRoot ); AssetDatabase.OpenAsset( clickedPrefabRoot );
} }
} }
} }
#endif
// Ping the clicked GameObject in the open prefab stage // Ping the clicked GameObject in the open prefab stage
Object selection, pingTarget; Object selection, pingTarget;
@@ -1339,7 +1311,7 @@ namespace AssetUsageDetectorNamespace
if( preferredHeight > 10f ) if( preferredHeight > 10f )
{ {
Vector2 size = position.size; Vector2 size = position.size;
position = Utilities.GetScreenFittedRect( new Rect( GUIUtility.GUIToScreenPoint( Event.current.mousePosition ) + new Vector2( size.x * -0.5f, 10f ), size ) ); position = Utilities.GetScreenFittedRect(new Rect(GUIUtility.GUIToScreenPoint(Event.current.mousePosition) + new Vector2(size.x * -0.5f, 10f), size), this);
shouldRepositionSelf = false; shouldRepositionSelf = false;
GUIUtility.ExitGUI(); GUIUtility.ExitGUI();
+106 -71
View File
@@ -2,9 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
#if UNITY_2018_1_OR_NEWER
using Unity.Collections; using Unity.Collections;
#endif
using UnityEditor; using UnityEditor;
using UnityEditor.SceneManagement; using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
@@ -37,19 +35,19 @@ namespace AssetUsageDetectorNamespace
typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ), typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ),
typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ), typeof( List<Bounds> ), typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ), typeof( List<Bounds> ),
typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> ), typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> ),
#if UNITY_2017_2_OR_NEWER
typeof( Vector3Int ), typeof( Vector2Int ), typeof( RectInt ), typeof( BoundsInt ), typeof( Vector3Int ), typeof( Vector2Int ), typeof( RectInt ), typeof( BoundsInt ),
typeof( Vector3Int[] ), typeof( Vector2Int[] ), typeof( RectInt[] ), typeof( BoundsInt[] ), typeof( Vector3Int[] ), typeof( Vector2Int[] ), typeof( RectInt[] ), typeof( BoundsInt[] ),
typeof( List<Vector3Int> ), typeof( List<Vector2Int> ), typeof( List<RectInt> ), typeof( List<BoundsInt> ) typeof( List<Vector3Int> ), typeof( List<Vector2Int> ), typeof( List<RectInt> ), typeof( List<BoundsInt> )
#endif
}; };
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace; private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
#if UNITY_2018_1_OR_NEWER
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace; private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
#endif
private static MethodInfo screenFittedRectGetter; private static MethodInfo screenFittedRectGetter;
private static FieldInfo editorWindowHostViewGetter;
private static PropertyInfo hostViewContainerWindowGetter;
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 ) );
private static readonly HashSet<string> folderContentsSet = new HashSet<string>(); private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
@@ -85,12 +83,7 @@ namespace AssetUsageDetectorNamespace
m_boxGUIStyle.hover.textColor = textColor; m_boxGUIStyle.hover.textColor = textColor;
m_boxGUIStyle.focused.textColor = textColor; m_boxGUIStyle.focused.textColor = textColor;
m_boxGUIStyle.active.textColor = textColor; m_boxGUIStyle.active.textColor = textColor;
#if !UNITY_2019_1_OR_NEWER || UNITY_2019_3_OR_NEWER
// On 2019.1 and 2019.2 versions, GUI.skin.button.fontSize returns 0 on some devices
// https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/page-3#post-7285954
m_boxGUIStyle.fontSize = ( m_boxGUIStyle.fontSize + GUI.skin.button.fontSize ) / 2; m_boxGUIStyle.fontSize = ( m_boxGUIStyle.fontSize + GUI.skin.button.fontSize ) / 2;
#endif
} }
return m_boxGUIStyle; return m_boxGUIStyle;
@@ -114,6 +107,77 @@ namespace AssetUsageDetectorNamespace
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) ); return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
} }
public static T GetPrefabParent<T>( this T obj ) where T : Object
{
return PrefabUtility.GetCorrespondingObjectFromSource( obj );
}
public static bool HasAnyPrefabOverrides( this Object obj )
{
if( obj.GetPrefabParent() == null )
return false;
return prefabHasAnyOverridesGetter( obj, false );
}
public static bool HasAnyPrefabOverrides( this GameObject gameObject )
{
if( gameObject.GetPrefabParent() == null )
return false;
if( !PrefabUtility.HasPrefabInstanceAnyOverrides( gameObject, false ) )
return false;
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 // Returns an enumerator to iterate through all asset paths in the folder
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset ) public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
{ {
@@ -151,7 +215,6 @@ namespace AssetUsageDetectorNamespace
{ {
// Pinging a prefab only works if the pinged object is the root of the prefab or a direct child of it. Pinging any grandchildren // Pinging a prefab only works if the pinged object is the root of the prefab or a direct child of it. Pinging any grandchildren
// of the prefab doesn't work; in which case, traverse the parent hierarchy until a pingable parent is reached // of the prefab doesn't work; in which case, traverse the parent hierarchy until a pingable parent is reached
#if UNITY_2018_3_OR_NEWER
Transform objTR = ( (GameObject) obj ).transform.root; Transform objTR = ( (GameObject) obj ).transform.root;
PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject ); PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject );
@@ -159,11 +222,7 @@ namespace AssetUsageDetectorNamespace
{ {
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject ); string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
#if UNITY_2020_1_OR_NEWER
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath ) if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath )
#else
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath )
#endif
{ {
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot ); GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot );
if( prefabStageGO != null ) if( prefabStageGO != null )
@@ -172,10 +231,8 @@ namespace AssetUsageDetectorNamespace
selection = objTR.gameObject; selection = objTR.gameObject;
} }
} }
#if UNITY_2019_1_OR_NEWER
else if( obj != objTR.gameObject ) else if( obj != objTR.gameObject )
selection = objTR.gameObject; selection = objTR.gameObject;
#endif
} }
else if( prefabAssetType == PrefabAssetType.Model ) else if( prefabAssetType == PrefabAssetType.Model )
{ {
@@ -183,11 +240,6 @@ namespace AssetUsageDetectorNamespace
while( objTR.parent != null && objTR.parent.parent != null ) while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent; objTR = objTR.parent;
} }
#else
Transform objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
#endif
pingTarget = objTR.gameObject; pingTarget = objTR.gameObject;
} }
@@ -282,11 +334,9 @@ namespace AssetUsageDetectorNamespace
if( fieldInfo.IsInitOnly ) if( fieldInfo.IsInitOnly )
return false; return false;
#if UNITY_2019_3_OR_NEWER
// SerializeReference makes even System.Object fields serializable // SerializeReference makes even System.Object fields serializable
if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) ) if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) )
return true; return true;
#endif
if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) ) if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) )
return false; return false;
@@ -320,7 +370,6 @@ namespace AssetUsageDetectorNamespace
else if( type.IsGenericType ) else if( type.IsGenericType )
{ {
// Generic types are allowed on 2020.1 and later // Generic types are allowed on 2020.1 and later
#if UNITY_2020_1_OR_NEWER
if( type.GetGenericTypeDefinition() == typeof( List<> ) ) if( type.GetGenericTypeDefinition() == typeof( List<> ) )
{ {
type = type.GetGenericArguments()[0]; type = type.GetGenericArguments()[0];
@@ -328,22 +377,8 @@ namespace AssetUsageDetectorNamespace
if( typeof( Object ).IsAssignableFrom( type ) ) if( typeof( Object ).IsAssignableFrom( type ) )
return true; return true;
} }
#else
if( type.GetGenericTypeDefinition() != typeof( List<> ) )
return false;
type = type.GetGenericArguments()[0];
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
#endif
} }
#if !UNITY_2020_1_OR_NEWER
if( type.IsGenericType )
return false;
#endif
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false ); return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
} }
@@ -353,11 +388,9 @@ namespace AssetUsageDetectorNamespace
if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum ) if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum )
return true; return true;
#if UNITY_2018_1_OR_NEWER
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed // Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
if( type.Namespace == nativeCollectionsNamespace ) if( type.Namespace == nativeCollectionsNamespace )
return true; return true;
#endif
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime // Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace ) if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
@@ -446,6 +479,15 @@ namespace AssetUsageDetectorNamespace
return stringBuilder.ToString(); 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 // Draw horizontal line inside OnGUI
public static void DrawSeparatorLine() public static void DrawSeparatorLine()
{ {
@@ -454,14 +496,25 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 4f ); GUILayout.Space( 4f );
} }
// Restricts the given Rect within the screen's bounds /// <summary>
public static Rect GetScreenFittedRect( Rect originalRect ) /// Restricts the given Rect within the screen's bounds.
{ /// </summary>
if( screenFittedRectGetter == null ) public static Rect GetScreenFittedRect(Rect originalRect, EditorWindow editorWindow)
screenFittedRectGetter = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.ContainerWindow" ).GetMethod( "FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ); {
screenFittedRectGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.ContainerWindow").GetMethod("FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
return (Rect) screenFittedRectGetter.Invoke( null, new object[3] { originalRect, true, true } ); if (screenFittedRectGetter.GetParameters().Length == 3)
} return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, true, true });
else
{
// New version introduced in Unity 2022.3.62f1, Unity 6.0.49f1 and Unity 6.1.0f1.
// Usage example: https://github.com/Unity-Technologies/UnityCsReference/blob/10f8718268a7e34844ba7d59792117c28d75a99b/Editor/Mono/EditorWindow.cs#L1264
editorWindowHostViewGetter ??= typeof(EditorWindow).GetField("m_Parent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
hostViewContainerWindowGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.HostView").GetProperty("window", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, originalRect.center, true, hostViewContainerWindowGetter.GetValue(editorWindowHostViewGetter.GetValue(editorWindow), null) });
}
}
// Check if all the objects inside the list are null // Check if all the objects inside the list are null
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch ) public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
@@ -471,7 +524,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < objectsToSearch.Count; i++ ) 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; return false;
} }
@@ -479,38 +532,20 @@ namespace AssetUsageDetectorNamespace
} }
// Check if all the objects inside the list are null // 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 ) if( objects == null )
return true; return true;
for( int i = 0; i < objects.Count; i++ ) for( int i = 0; i < objects.Count; i++ )
{ {
if( objects[i] != null && !objects[i].Equals( null ) ) if( objects[i] != null )
return false; return false;
} }
return true; 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 // Returns true is str starts with prefix
public static bool StartsWithFast( this string str, string prefix ) public static bool StartsWithFast( this string str, string prefix )
{ {
@@ -9,14 +9,14 @@ namespace AssetUsageDetectorNamespace
public delegate object VariableGetVal( object obj ); public delegate object VariableGetVal( object obj );
// Custom struct to hold a variable, its important properties and its getter function // Custom struct to hold a variable, its important properties and its getter function
public struct VariableGetterHolder public readonly struct VariableGetterHolder
{ {
public readonly MemberInfo variable; public readonly MemberInfo variable;
public readonly bool isSerializable; public readonly bool isSerializable;
private readonly VariableGetVal getter; private readonly VariableGetVal getter;
public string Name { get { return variable.Name; } } public readonly string Name { get { return variable.Name; } }
public bool IsProperty { get { return variable is PropertyInfo; } } public readonly bool IsProperty { get { return variable is PropertyInfo; } }
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable ) public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
{ {
@@ -32,7 +32,7 @@ namespace AssetUsageDetectorNamespace
this.getter = getter; this.getter = getter;
} }
public object Get( object obj ) public readonly object Get( object obj )
{ {
try try
{ {
+1 -1
View File
@@ -1,4 +1,4 @@
= Asset Usage Detector (v2.5.4) = = Asset Usage Detector (v2.5.7) =
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com E-mail: yasirkula@gmail.com
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "com.yasirkula.assetusagedetector", "name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector", "displayName": "Asset Usage Detector",
"version": "2.5.4", "version": "2.5.7",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector", "documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases", "changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt", "licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",