Compare commits

..

21 Commits

Author SHA1 Message Date
Süleyman Yasir KULA 466a152ba6 Update README.md 2023-05-07 21:49:19 +03:00
yasirkula 5eda0c1cb0 Added VFX Graph support 2023-05-07 21:47:22 +03:00
yasirkula 42e3278129 Fixed not being able to ping some asset search results in Project window (in particular, VFX graph search results) 2023-05-07 21:38:28 +03:00
yasirkula f6a999f053 Fixed an exception that occurs when a VFX Graph window is open and the open VFX Graph asset is searched for references (there may be other similar edge cases, as well) 2023-05-07 21:37:38 +03:00
yasirkula 8441e4701c Addressables support no longer requires manual modifications 2023-05-07 21:36:05 +03:00
yasirkula d57a707678 Fixed exceptions while searching for some URP assets' references due to their overriden GetHashCode functions 2023-03-18 15:12:13 +03:00
yasirkula 3fa3344507 Fixed #33 2023-03-18 15:09:37 +03:00
yasirkula 8072530c2c Added experimental Addressables support (requires manual modifications) (closed #29) 2022-10-15 17:11:42 +03:00
yasirkula 28a73e2843 Shaders are searched for #include_with_pragmas references in addition to #include references 2022-09-23 14:17:52 +03:00
yasirkula c7e52466ef Added Collapse All button to Asset Usage Detector window's context menu that collapses all search result groups at once 2022-09-23 14:16:52 +03:00
yasirkula 875f3e6794 Fixed right clicking Unused Objects group throwing an exception if that search result group hasn't been expanded yet 2022-09-23 14:16:04 +03:00
yasirkula 635d0653fa Material's color and mainTexture properties aren't searched at runtime since they're searched by SearchMaterial anyways and they can actually throw errors in the Console if the corresponding shader property doesn't exist 2022-09-23 14:15:13 +03:00
yasirkula cb4454b493 - Terrains are now searched properly
- Fixed an error on latest Unity versions when clicking the "Reset Search" button
2022-07-23 21:53:11 +03:00
yasirkula dfb8541605 Fixed compiler errors on 2021.2 and later 2022-04-24 15:14:47 +03:00
yasirkula 4b146280ab (Experimental)(#14) Added SearchRefactoring parameter to AssetUsageDetector (only useful while triggering the search via Scripting API). It allows getting notified of found references during the search (some references like Assembly Definition File references or Shader Graph references aren't supported) and in most cases, refactoring them (e.g. changing all usages of a searched object with something else or null). Disabling "Lazy Scene Search" is recommended while using this feature and it's advised to backup your project beforehand 2022-01-05 10:18:17 +03:00
yasirkula 8a6fe822d6 Materials instantiated (cloned) at runtime are now searched correctly 2022-01-05 10:17:07 +03:00
yasirkula c9ceab6085 Fixed Settings not fitting inside Preferences window on older Unity versions 2022-01-04 23:24:55 +03:00
yasirkula 4fddcb7b80 Simplified "Can't search unloaded scenes in play mode" warnings 2022-01-04 23:24:49 +03:00
yasirkula 001df6eb6c Fixed locked AssetUsageDetector windows entering an inconsistent state after relaunching the editor 2022-01-04 23:24:30 +03:00
yasirkula 60f8d30810 Undo'ed a previous change that resulted in some particle system variables not being searched in play mode 2022-01-04 23:20:38 +03:00
yasirkula c9dbd2d201 Fixed README.txt link in documentation 2022-01-01 21:47:43 +03:00
14 changed files with 1128 additions and 141 deletions
+28 -2
View File
@@ -30,16 +30,42 @@ There are 5 ways to install this plugin:
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!** - Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- or, right click an object and select **Search For References** - or, right click an object and select **Search For References**
- To learn how to interpret the search results and for more instructions, please see the included [README.txt](Plugins/AssetUsageDetector/README.txt) file - To learn how to interpret the search results and for more instructions, please see the included [README.txt](../Plugins/AssetUsageDetector/README.txt) file
- You can tweak most settings/colors via *Project Settings/yasirkula/Asset Usage Detector* page (on older versions, this menu is located at *Preferences* window) - You can tweak most settings/colors via *Project Settings/yasirkula/Asset Usage Detector* page (on older versions, this menu is located at *Preferences* window)
![SearchResults1](Images/SearchResults1Dark.png) ![SearchResults1](Images/SearchResults1Dark.png)
![SearchResults2](Images/SearchResults2Dark.png) ![SearchResults2](Images/SearchResults2Dark.png)
## SEARCH REFACTORING
While searching for references using the Scripting API, it's possible to get notified of the found references *during* the search (some references like *Assembly Definition File* references or *Shader Graph* references aren't supported) and in most cases, refactor them (e.g. changing all usages of a searched object with something else or *null*). Disabling *Lazy Scene Search* is recommended while using this feature and it's advised to backup your project beforehand.
To initiate a search using the Scripting API, you need to put your script either in *Editor* folder or add `AssetUsageDetector.Editor` as reference to your *Assembly Definition File*. Then, you can either create a new instance of `AssetUsageDetectorNamespace.AssetUsageDetector` object and call its `Run` method, or call the `AssetUsageDetectorNamespace.AssetUsageDetectorWindow.ShowAndSearch` method. In either case, you'll be handling the search refactoring in the **searchRefactoring** callback:
```csharp
void ReplaceFontUsages( Font from, Font to )
{
AssetUsageDetector assetUsageDetector = new AssetUsageDetector();
assetUsageDetector.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = new Object[] { from },
lazySceneSearch = false,
searchRefactoring = ( searchMatch ) =>
{
Debug.LogFormat( "Found a {0} reference from {1} to {2}", searchMatch.GetType().Name, searchMatch.Source, searchMatch.Value );
searchMatch.ChangeValue( to );
}
} );
}
```
**NOTE:** Refactored references won't be reflected to the returned search results, old references will continue to be displayed. After saving the changes (modified scenes) and initiating another search, correct search results will be shown.
**NOTE2:** After refactoring the references, consider performing a normal search to see if all references were correctly refactored. If some references weren't refactored (even though they could've been), feel free to report it.
## KNOWN LIMITATIONS ## KNOWN LIMITATIONS
- *Addressables* aren't supported
- *static* variables aren't searched - *static* variables aren't searched
- *Resources.Load* usages can't be found - *Resources.Load* usages can't be found
- *GUIText* materials aren't searched - *GUIText* materials aren't searched
@@ -1,6 +1,9 @@
{ {
"name": "AssetUsageDetector.Editor", "name": "AssetUsageDetector.Editor",
"references": [], "rootNamespace": "",
"references": [
"Unity.Addressables"
],
"includePlatforms": [ "includePlatforms": [
"Editor" "Editor"
], ],
@@ -10,6 +13,17 @@
"precompiledReferences": [], "precompiledReferences": [],
"autoReferenced": true, "autoReferenced": true,
"defineConstraints": [], "defineConstraints": [],
"versionDefines": [], "versionDefines": [
{
"name": "com.unity.addressables",
"expression": "0.0.0",
"define": "ASSET_USAGE_ADDRESSABLES"
},
{
"name": "com.unity.visualeffectgraph",
"expression": "0.0.0",
"define": "ASSET_USAGE_VFX_GRAPH"
}
],
"noEngineReferences": false "noEngineReferences": false
} }
@@ -10,7 +10,7 @@ using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER #if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif #endif
@@ -44,7 +44,12 @@ namespace AssetUsageDetectorNamespace
public bool searchUnusedMaterialProperties = true; public bool searchUnusedMaterialProperties = true;
public SearchRefactoring searchRefactoring = null;
public bool lazySceneSearch = true; public bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
public bool addressablesSupport = false;
#endif
public bool calculateUnusedObjects = false; public bool calculateUnusedObjects = false;
public bool hideDuplicateRows = true; public bool hideDuplicateRows = true;
public bool hideReduntantPrefabVariantLinks = true; public bool hideReduntantPrefabVariantLinks = true;
@@ -53,6 +58,8 @@ namespace AssetUsageDetectorNamespace
} }
#endregion #endregion
private Parameters searchParameters;
// A set that contains the searched scene object(s), asset(s) and their sub-assets (if any) // A set that contains the searched scene object(s), asset(s) and their sub-assets (if any)
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>(); private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
// Scenes of scene object(s) in objectsToSearchSet // Scenes of scene object(s) in objectsToSearchSet
@@ -78,14 +85,9 @@ namespace AssetUsageDetectorNamespace
// Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function) // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
private readonly List<object> callStack = new List<object>( 64 ); private readonly List<object> callStack = new List<object>( 64 );
private int searchDepthLimit; // Depth limit for recursively searching variables of objects
private Object currentSearchedObject; private Object currentSearchedObject;
private int currentDepth; private int currentDepth;
private bool searchUnusedMaterialProperties;
private bool dontSearchInSourceAssets;
private bool searchingSourceAssets; private bool searchingSourceAssets;
private bool isInPlayMode; private bool isInPlayMode;
@@ -166,6 +168,8 @@ namespace AssetUsageDetectorNamespace
try try
{ {
this.searchParameters = searchParameters;
// Initialize commonly used variables // Initialize commonly used variables
searchResult = new List<SearchResultGroup>(); // Overall search results searchResult = new List<SearchResultGroup>(); // Overall search results
@@ -174,10 +178,6 @@ namespace AssetUsageDetectorNamespace
searchedObjectsCount = 0; searchedObjectsCount = 0;
searchStartTime = EditorApplication.timeSinceStartup; searchStartTime = EditorApplication.timeSinceStartup;
searchDepthLimit = searchParameters.searchDepthLimit;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchedObjects.Clear(); searchedObjects.Clear();
searchedUnityObjects.Clear(); searchedUnityObjects.Clear();
animationClipUniqueBindings.Clear(); animationClipUniqueBindings.Clear();
@@ -321,16 +321,28 @@ namespace AssetUsageDetectorNamespace
openScenes.Add( scene.path ); openScenes.Add( scene.path );
} }
List<string> skippedScenes = new List<string>( scenesToSearch.Count );
scenesToSearch.RemoveWhere( ( path ) => scenesToSearch.RemoveWhere( ( path ) =>
{ {
if( !openScenes.Contains( path ) ) if( !openScenes.Contains( path ) )
{ {
Debug.Log( "Can't search unloaded scenes while in play mode, skipped " + path ); skippedScenes.Add( path );
return true; return true;
} }
return false; return false;
} ); } );
if( skippedScenes.Count > 0 )
{
StringBuilder sb = Utilities.stringBuilder;
sb.Length = 0;
sb.Append( "Can't search unloaded scenes while in play mode, skipped " ).Append( skippedScenes.Count ).AppendLine( " scene(s):" );
for( int i = 0; i < skippedScenes.Count; i++ )
sb.Append( "- " ).AppendLine( skippedScenes[i] );
Debug.Log( sb.ToString() );
}
} }
// Initialize data used by search functions // Initialize data used by search functions
@@ -338,7 +350,7 @@ namespace AssetUsageDetectorNamespace
// Initialize the nodes of searched asset(s) // Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet ) foreach( Object obj in objectsToSearchSet )
searchedUnityObjects.Add( obj.GetHashCode(), PopReferenceNode( obj ) ); searchedUnityObjects.Add( obj.GetInstanceID(), PopReferenceNode( obj ) );
// Progressbar values // Progressbar values
int searchProgress = 0; int searchProgress = 0;
@@ -533,7 +545,7 @@ namespace AssetUsageDetectorNamespace
} }
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast // Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
if( !dontSearchInSourceAssets ) if( !searchParameters.dontSearchInSourceAssets )
{ {
searchingSourceAssets = true; searchingSourceAssets = true;
@@ -660,7 +672,7 @@ namespace AssetUsageDetectorNamespace
else else
{ {
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent ) for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent )
usedObjectPathsSet.Add( parent.gameObject.GetHashCode().ToString() ); usedObjectPathsSet.Add( parent.gameObject.GetInstanceID().ToString() );
} }
} }
} }
@@ -727,13 +739,13 @@ namespace AssetUsageDetectorNamespace
if( !searchedTopmostGameObject ) if( !searchedTopmostGameObject )
{ {
if( obj is GameObject ) if( obj is GameObject )
unusedMainObjectNodes[obj.GetHashCode().ToString()] = node; unusedMainObjectNodes[obj.GetInstanceID().ToString()] = node;
else else
currentSearchResultGroup.AddReference( node ); currentSearchResultGroup.AddReference( node );
} }
else // List child GameObject scene objects under their parent GameObject else // List child GameObject scene objects under their parent GameObject
{ {
string dictionaryKey = searchedTopmostGameObject.GetHashCode().ToString(); string dictionaryKey = searchedTopmostGameObject.GetInstanceID().ToString();
List<ReferenceNode> unusedSubObjectNodesAtPath; List<ReferenceNode> unusedSubObjectNodesAtPath;
if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) ) if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) )
unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 ); unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
@@ -821,7 +833,7 @@ namespace AssetUsageDetectorNamespace
if( !string.IsNullOrEmpty( assetPath ) ) if( !string.IsNullOrEmpty( assetPath ) )
{ {
assetsToSearchPathsSet.Add( assetPath ); assetsToSearchPathsSet.Add( assetPath );
if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) ) if( searchParameters.dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
excludedAssetsPathsSet.Add( assetPath ); excludedAssetsPathsSet.Add( assetPath );
} }
@@ -973,9 +985,13 @@ namespace AssetUsageDetectorNamespace
if( obj == null || obj.Equals( null ) ) if( obj == null || obj.Equals( null ) )
return null; return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack // Avoid recursion (which leads to stackoverflow exception) using a stack (initially, I was using callStack.ContainsFast
if( callStack.ContainsFast( obj ) ) // here but it returned false for objects that do exist in the call stack if VFX Graph window was open)
return null; for( int i = callStack.Count - 1; i >= 0; i-- )
{
if( callStack[i].Equals( obj ) )
return null;
}
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj ); bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
@@ -1000,14 +1016,14 @@ namespace AssetUsageDetectorNamespace
{ {
if( assetsToSearchSet.Count == 0 ) if( assetsToSearchSet.Count == 0 )
{ {
searchedUnityObjects.Add( unityObject.GetHashCode(), null ); searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null; return null;
} }
assetPath = AssetDatabase.GetAssetPath( unityObject ); assetPath = AssetDatabase.GetAssetPath( unityObject );
if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) ) if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) )
{ {
searchedUnityObjects.Add( unityObject.GetHashCode(), null ); searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null; return null;
} }
} }
@@ -1015,7 +1031,7 @@ namespace AssetUsageDetectorNamespace
callStack.Add( unityObject ); callStack.Add( unityObject );
// Search the Object in detail // Search the Object in detail
Func<Object, ReferenceNode> searchFunction; Func<object, ReferenceNode> searchFunction;
if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) ) if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) )
result = searchFunction( unityObject ); result = searchFunction( unityObject );
else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) ) else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) )
@@ -1050,7 +1066,7 @@ namespace AssetUsageDetectorNamespace
else else
{ {
// Comply with the recursive search limit // Comply with the recursive search limit
if( currentDepth >= searchDepthLimit ) if( currentDepth >= searchParameters.searchDepthLimit )
return null; return null;
callStack.Add( obj ); callStack.Add( obj );
@@ -1077,13 +1093,13 @@ namespace AssetUsageDetectorNamespace
if( !searchingSourceAsset ) if( !searchingSourceAsset )
{ {
if( obj is Object ) if( obj is Object )
searchedUnityObjects.Add( unityObject.GetHashCode(), result ); searchedUnityObjects.Add( unityObject.GetInstanceID(), result );
else else
searchedObjects.Add( GetNodeObjectHash( obj ), result ); searchedObjects.Add( GetNodeObjectHash( obj ), result );
} }
else if( result != null ) else if( result != null )
{ {
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetHashCode()] ); result.CopyReferencesTo( searchedUnityObjects[unityObject.GetInstanceID()] );
PoolReferenceNode( result ); PoolReferenceNode( result );
} }
} }
@@ -1094,6 +1110,11 @@ namespace AssetUsageDetectorNamespace
// Check if the asset at specified path depends on any of the references // Check if the asset at specified path depends on any of the references
private bool AssetHasAnyReference( string assetPath ) private bool AssetHasAnyReference( string assetPath )
{ {
#if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport )
return true;
#endif
if( assetsToSearchPathsSet.Contains( assetPath ) ) if( assetsToSearchPathsSet.Contains( assetPath ) )
return true; return true;
@@ -1212,7 +1233,7 @@ namespace AssetUsageDetectorNamespace
{ {
if( nodeObject is Object ) if( nodeObject is Object )
{ {
if( searchedUnityObjects.TryGetValue( nodeObject.GetHashCode(), out referenceNode ) ) if( searchedUnityObjects.TryGetValue( ( (Object) nodeObject ).GetInstanceID(), out referenceNode ) )
return true; return true;
} }
else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) ) else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) )
@@ -1228,7 +1249,7 @@ namespace AssetUsageDetectorNamespace
ReferenceNode result; ReferenceNode result;
if( nodeObject is Object ) if( nodeObject is Object )
{ {
int hash = nodeObject.GetHashCode(); int hash = ( (Object) nodeObject ).GetInstanceID();
if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null ) if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null )
{ {
result = PopReferenceNode( nodeObject ); result = PopReferenceNode( nodeObject );
File diff suppressed because it is too large Load Diff
@@ -171,7 +171,11 @@ namespace AssetUsageDetectorNamespace
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();
@@ -5,7 +5,10 @@ using UnityEditor;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER #if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif #endif
@@ -28,6 +31,7 @@ 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";
private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
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_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks"; private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks";
@@ -46,6 +50,8 @@ 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
private bool m_isLocked; private bool m_isLocked;
private bool IsLocked private bool IsLocked
{ {
@@ -59,6 +65,7 @@ namespace AssetUsageDetectorNamespace
} }
} }
} }
#pragma warning restore 0649
private Phase currentPhase = Phase.Setup; private Phase currentPhase = Phase.Setup;
@@ -77,6 +84,9 @@ namespace AssetUsageDetectorNamespace
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool lazySceneSearch = true; private bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
private bool addressablesSupport = false;
#endif
private bool searchNonSerializableVariables = true; private bool searchNonSerializableVariables = true;
private bool searchUnusedMaterialProperties = true; private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false; private bool calculateUnusedObjects = false;
@@ -87,6 +97,8 @@ namespace AssetUsageDetectorNamespace
private BindingFlags fieldModifiers, propertyModifiers; private BindingFlags fieldModifiers, propertyModifiers;
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer(); private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false ); private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false ); private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
@@ -144,6 +156,14 @@ namespace AssetUsageDetectorNamespace
objectsToSearch[i].RefreshSubAssets(); objectsToSearch[i].RefreshSubAssets();
} ); } );
} }
else if( currentPhase == Phase.Complete )
{
if( searchResult != null && searchResult.NumberOfGroups > 0 )
{
contextMenu.AddSeparator( "" );
contextMenu.AddItem( new GUIContent( "Collapse All" ), false, searchResult.CollapseAllSearchResultGroups );
}
}
} }
// Shows lock button at the top-right corner // Shows lock button at the top-right corner
@@ -166,6 +186,8 @@ namespace AssetUsageDetectorNamespace
if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) ) if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
{ {
window.Show(); window.Show();
window.Focus();
return window; return window;
} }
@@ -188,6 +210,8 @@ namespace AssetUsageDetectorNamespace
} }
window.Show( true ); window.Show( true );
window.Focus();
return window; return window;
} }
@@ -297,7 +321,11 @@ namespace AssetUsageDetectorNamespace
propertyModifiers = searchParameters.propertyModifiers; propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables; searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties; searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch; lazySceneSearch = searchParameters.lazySceneSearch;
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = searchParameters.addressablesSupport;
#endif
calculateUnusedObjects = searchParameters.calculateUnusedObjects; calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows; hideDuplicateRows = searchParameters.hideDuplicateRows;
hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks; hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks;
@@ -377,6 +405,9 @@ namespace AssetUsageDetectorNamespace
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables ); EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties ); EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch ); EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
EditorPrefs.SetBool( PREFS_ADDRESSABLES_SUPPORT, addressablesSupport );
#endif
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects ); EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows ); EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks ); EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks );
@@ -396,6 +427,9 @@ namespace AssetUsageDetectorNamespace
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true ); searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true ); searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true ); lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = EditorPrefs.GetBool( PREFS_ADDRESSABLES_SUPPORT, false );
#endif
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false ); calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true ); hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true ); hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true );
@@ -448,7 +482,10 @@ namespace AssetUsageDetectorNamespace
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." ); GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) ) if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase(); ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
} }
else if( currentPhase == Phase.Setup ) else if( currentPhase == Phase.Setup )
{ {
@@ -527,7 +564,14 @@ namespace AssetUsageDetectorNamespace
GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.backgroundColor = c; GUI.backgroundColor = c;
#if ASSET_USAGE_ADDRESSABLES
EditorGUI.BeginDisabledGroup( addressablesSupport );
#endif
lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch ); lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
EditorGUI.EndDisabledGroup();
addressablesSupport = WordWrappingToggleLeft( "Addressables support (Experimental) (WARNING: 'Lazy scene search' will be disabled) (slower search)", addressablesSupport );
#endif
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects ); 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 #if UNITY_2018_3_OR_NEWER
@@ -563,7 +607,10 @@ namespace AssetUsageDetectorNamespace
GUI.enabled = true; GUI.enabled = true;
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) ) if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase(); ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
if( searchResult == null ) if( searchResult == null )
{ {
@@ -659,7 +706,13 @@ namespace AssetUsageDetectorNamespace
//searchDepthLimit = searchDepthLimit, //searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables, //searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties, searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
#if ASSET_USAGE_ADDRESSABLES
lazySceneSearch = lazySceneSearch && !addressablesSupport,
addressablesSupport = addressablesSupport,
#else
lazySceneSearch = lazySceneSearch, lazySceneSearch = lazySceneSearch,
#endif
calculateUnusedObjects = calculateUnusedObjects, calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows, hideDuplicateRows = hideDuplicateRows,
hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks, hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks,
@@ -669,6 +722,9 @@ namespace AssetUsageDetectorNamespace
currentPhase = Phase.Complete; currentPhase = Phase.Complete;
// We really don't want SearchRefactoring to affect next searches unless the search is initiated via ShowAndSearch again
searchRefactoring = null;
if( AssetUsageDetectorSettings.ShowCustomTooltip ) if( AssetUsageDetectorSettings.ShowCustomTooltip )
wantsMouseMove = wantsMouseEnterLeaveWindow = true; wantsMouseMove = wantsMouseEnterLeaveWindow = true;
} }
@@ -0,0 +1,382 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
public delegate void SearchRefactoring( SearchMatch match );
public abstract class SearchMatch
{
public readonly object Source;
public readonly Object Context; // Almost always equal to Source. This is the Object that needs to be dirtied (if not null) to notify Unity of changes to Value
public Object Value { get; private set; }
protected SearchMatch( object source, Object value )
{
Source = source;
Context = source as Object;
Value = value;
}
protected SearchMatch( object source, Object value, Object context ) : this( source, value )
{
Context = context;
}
public void ChangeValue( Object newValue )
{
if( newValue == Value )
return;
if( Context && ( Context.hideFlags & HideFlags.NotEditable ) == HideFlags.NotEditable )
{
Debug.LogWarning( "Can't change value of read-only Object: " + Context, Context );
return;
}
try
{
bool setContextDirty;
if( ChangeValue( newValue, out setContextDirty ) )
OnValueChanged( newValue, setContextDirty );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
protected abstract bool ChangeValue( Object newValue, out bool setContextDirty );
public void OnValueChanged( Object newValue, bool setContextDirty = true )
{
Value = newValue;
if( setContextDirty )
{
if( Context )
{
if( AssetDatabase.Contains( Context ) )
EditorUtility.SetDirty( Context );
else if( !EditorApplication.isPlaying )
{
EditorUtility.SetDirty( Context );
if( Context is Component )
EditorSceneManager.MarkSceneDirty( ( (Component) Context ).gameObject.scene );
else if( Context is GameObject )
EditorSceneManager.MarkSceneDirty( ( (GameObject) Context ).scene );
else
EditorSceneManager.MarkAllScenesDirty();
}
}
else if( !EditorApplication.isPlaying )
EditorSceneManager.MarkAllScenesDirty();
}
}
}
public abstract class GenericSearchMatch : SearchMatch
{
public delegate void SetterFunction( Object newValue );
public readonly SetterFunction Setter;
internal GenericSearchMatch( object source, Object value, SetterFunction setter ) : base( source, value ) { Setter = setter; }
internal GenericSearchMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context ) { Setter = setter; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
Setter( newValue );
setContextDirty = true;
return true;
}
}
public abstract class ReadOnlySearchMatch : SearchMatch
{
internal ReadOnlySearchMatch( object source, Object value ) : base( source, value ) { }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
Debug.LogWarning( "Can't change value of " + GetType().Name );
setContextDirty = false;
return false;
}
}
/// <summary>
/// - Source: Object whose SerializedProperty points to Value
/// - Value: Referenced object
/// - SerializedProperty: The SerializedProperty that points to Value
/// </summary>
public class SerializedPropertyMatch : SearchMatch
{
public readonly SerializedProperty SerializedProperty; // Next or NextVisible mustn't be called with this SerializedProperty
internal SerializedPropertyMatch( Object source, Object value, SerializedProperty property ) : base( source, value ) { SerializedProperty = property; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = true;
switch( SerializedProperty.propertyType )
{
case SerializedPropertyType.ObjectReference:
SerializedProperty.objectReferenceValue = newValue;
if( SerializedProperty.objectReferenceValue != newValue )
{
Debug.LogWarning( "Couldn't cast " + newValue.GetType() + " to " + SerializedProperty.type );
SerializedProperty.objectReferenceValue = Value;
return false;
}
break;
case SerializedPropertyType.ExposedReference:
SerializedProperty.exposedReferenceValue = newValue;
if( SerializedProperty.exposedReferenceValue != newValue )
{
Debug.LogWarning( "Couldn't cast " + newValue.GetType() + " to " + SerializedProperty.type );
SerializedProperty.exposedReferenceValue = Value;
return false;
}
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference: SerializedProperty.managedReferenceValue = newValue; break;
#endif
}
SerializedProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo();
return true;
}
}
/// <summary>
/// - Source: Object whose variable points to Value
/// - Value: Referenced object
/// - Variable: FieldInfo, PropertyInfo or IEnumerable (ChangeValue may not work for all IEnumerables)
/// </summary>
public class ReflectionMatch : SearchMatch
{
public readonly object Variable;
internal ReflectionMatch( object source, Object value, object variable ) : base( source, value ) { Variable = variable; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = true;
if( Variable is FieldInfo )
( (FieldInfo) Variable ).SetValue( Source, newValue );
else if( Variable is PropertyInfo )
{
PropertyInfo property = (PropertyInfo) Variable;
if( !property.CanWrite )
{
Debug.LogWarning( "Property is read-only: " + property.DeclaringType.FullName + "." + property.Name );
return false;
}
property.SetValue( Source, newValue, null );
}
else if( Variable is IList )
{
IList list = (IList) Variable;
for( int i = list.Count - 1; i >= 0; i-- )
{
if( ReferenceEquals( list[i], Value ) )
list[i] = newValue;
}
}
else if( Variable is IDictionary )
{
IDictionary dictionary = (IDictionary) Variable;
bool dictionaryModified;
do
{
dictionaryModified = false;
foreach( object dictKey in dictionary.Keys )
{
object dictValue = dictionary[dictKey];
if( ReferenceEquals( dictKey, Value ) )
{
dictionary.Remove( dictKey );
if( newValue )
dictionary[newValue] = dictValue;
dictionaryModified = true;
break;
}
else if( ReferenceEquals( dictValue, Value ) )
{
dictionary[dictKey] = newValue;
dictionaryModified = true;
break;
}
}
} while( dictionaryModified );
}
else
{
Debug.LogWarning( "Can't change value of " + Variable.GetType().Name );
return false;
}
return true;
}
}
/// <summary>
/// - Source: MonoImporter (for scripts) or ShaderImporter
/// - Value: Default value assigned to Source's specified variable in the Inspector
/// - Variable: The variable of Source that Value is assigned to as default value
/// - MonoScriptAllVariables: All variables of Source script if it's MonoImporter
/// </summary>
public class AssetImporterDefaultValueMatch : SearchMatch
{
public readonly string Variable;
public readonly VariableGetterHolder[] MonoScriptAllVariables;
internal AssetImporterDefaultValueMatch( Object source, Object value, string variable, VariableGetterHolder[] monoScriptAllVariables ) : base( source, value )
{
Variable = variable;
MonoScriptAllVariables = monoScriptAllVariables;
}
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = false;
if( Source is MonoImporter )
{
MonoImporter monoImporter = (MonoImporter) Source;
List<string> variableNames = new List<string>( 8 );
List<Object> variableValues = new List<Object>( 8 );
for( int i = 0; i < MonoScriptAllVariables.Length; i++ )
{
if( MonoScriptAllVariables[i].isSerializable && !MonoScriptAllVariables[i].IsProperty )
{
Object variableDefaultValue = monoImporter.GetDefaultReference( MonoScriptAllVariables[i].Name );
if( variableDefaultValue == Value && MonoScriptAllVariables[i].Name == Variable )
variableDefaultValue = newValue;
variableNames.Add( MonoScriptAllVariables[i].Name );
variableValues.Add( variableDefaultValue );
}
}
monoImporter.SetDefaultReferences( variableNames.ToArray(), variableValues.ToArray() );
EditorApplication.delayCall += () => AssetDatabase.ImportAsset( monoImporter.assetPath ); // If code recompiles during search, it will break the search. Give it a 1 frame delay
}
else if( Source is ShaderImporter )
{
ShaderImporter shaderImporter = (ShaderImporter) Source;
Shader shader = shaderImporter.GetShader();
List<string> textureNames = new List<string>( 16 );
List<Texture> textureValues = new List<Texture>( 16 );
#if UNITY_2018_1_OR_NEWER
List<string> nonModifiableTextureNames = new List<string>( 16 );
List<Texture> nonModifiableTextureValues = new List<Texture>( 16 );
#endif
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
for( int i = 0; i < shaderPropertyCount; i++ )
{
if( ShaderUtil.GetPropertyType( shader, i ) != ShaderUtil.ShaderPropertyType.TexEnv )
continue;
string propertyName = ShaderUtil.GetPropertyName( shader, i );
#if UNITY_2018_1_OR_NEWER
if( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) )
{
Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable )
propertyDefaultValue = (Texture) newValue;
nonModifiableTextureNames.Add( propertyName );
nonModifiableTextureValues.Add( propertyDefaultValue );
}
else
#endif
{
Texture propertyDefaultValue = shaderImporter.GetDefaultTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable )
propertyDefaultValue = (Texture) newValue;
textureNames.Add( propertyName );
textureValues.Add( propertyDefaultValue );
}
}
shaderImporter.SetDefaultTextures( textureNames.ToArray(), textureValues.ToArray() );
#if UNITY_2018_1_OR_NEWER
shaderImporter.SetNonModifiableTextures( nonModifiableTextureNames.ToArray(), nonModifiableTextureValues.ToArray() );
#endif
AssetDatabase.ImportAsset( shaderImporter.assetPath );
}
else
{
Debug.LogWarning( "Can't change default value of: " + Source.GetType() );
return false;
}
return true;
}
}
/// <summary>
/// - Source: Animation, Animator, AnimatorStateMachine, AnimatorState, AnimatorControllerLayer, BlendTree, PlayableDirector* or AnimationClip*
/// - Context: If Source is AnimatorControllerLayer, then its RuntimeAnimatorController. Otherwise, equal to Source
/// - Value: AnimationClip, AnimatorController or AvatarMask used in Source (*for PlayableDirector and AnimationClip, it can be any Object value)
/// </summary>
public class AnimationSystemMatch : GenericSearchMatch
{
internal AnimationSystemMatch( object source, Object value, SetterFunction setter ) : base( source, value, setter ) { }
internal AnimationSystemMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context, setter ) { }
}
/// <summary>
/// - Source: GameObject, AnimatorStateMachine or AnimatorState
/// - Value: The attached behaviour's source script (C# script or DLL, i.e. MonoScript)
/// - Behaviour: The attached behaviour (MonoBehaviour or StateMachineBehaviour)
/// </summary>
public class BehaviourUsageMatch : ReadOnlySearchMatch
{
public readonly Object Behaviour;
internal BehaviourUsageMatch( Object source, MonoScript value, Object behaviour ) : base( source, value ) { Behaviour = behaviour; }
}
/// <summary>
/// - Source: GameObject Instance
/// - Value: Prefab of that GameObject
/// </summary>
public class PrefabMatch : ReadOnlySearchMatch
{
internal PrefabMatch( Object source, Object value ) : base( source, value ) { }
}
/// <summary>
/// - Source: Object that references Value
/// - Value: Matched object
/// </summary>
public class OtherSearchMatch : GenericSearchMatch
{
internal OtherSearchMatch( object source, Object value, SetterFunction setter ) : base( source, value, setter ) { }
internal OtherSearchMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context, setter ) { }
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3d15ef8bd8f7c7c4e8d228c99713b7eb
timeCreated: 1641132238
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -371,9 +371,15 @@ namespace AssetUsageDetectorNamespace
return scrollPosition; return scrollPosition;
} }
public int IndexOf( SearchResultGroup searchResult ) public int IndexOf( SearchResultGroup searchResultGroup )
{ {
return result.IndexOf( searchResult ); return result.IndexOf( searchResultGroup );
}
public void CollapseAllSearchResultGroups()
{
for( int i = 0; i < result.Count; i++ )
result[i].Collapse();
} }
public void CancelDelayedTreeViewTooltip() public void CancelDelayedTreeViewTooltip()
@@ -600,6 +606,11 @@ namespace AssetUsageDetectorNamespace
treeViewSearchField = null; treeViewSearchField = null;
} }
public void Collapse()
{
IsExpanded = false;
}
// Initializes commonly used variables of the nodes // Initializes commonly used variables of the nodes
public void InitializeNodes( HashSet<Object> objectsToSearchSet ) public void InitializeNodes( HashSet<Object> objectsToSearchSet )
{ {
@@ -725,7 +736,7 @@ namespace AssetUsageDetectorNamespace
if( searchResult != null ) if( searchResult != null )
contextMenu.AddItem( new GUIContent( "Hide" ), false, () => searchResult.RemoveSearchResultGroup( this ) ); contextMenu.AddItem( new GUIContent( "Hide" ), false, () => searchResult.RemoveSearchResultGroup( this ) );
if( references.Count > 0 ) if( references.Count > 0 && treeView != null )
{ {
if( contextMenu.GetItemCount() > 0 ) if( contextMenu.GetItemCount() > 0 )
contextMenu.AddSeparator( "" ); contextMenu.AddSeparator( "" );
@@ -5,7 +5,10 @@ using System.Text;
using UnityEditor; using UnityEditor;
using UnityEditor.IMGUI.Controls; using UnityEditor.IMGUI.Controls;
using UnityEngine; using UnityEngine;
#if UNITY_2018_3_OR_NEWER #if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif #endif
@@ -296,7 +299,7 @@ namespace AssetUsageDetectorNamespace
if( linkDescriptions.Count > 0 ) if( linkDescriptions.Count > 0 )
{ {
Object prefabObject = PrefabUtility.GetCorrespondingObjectFromSource( unityObject ); Object prefabObject = PrefabUtility.GetCorrespondingObjectFromSource( unityObject );
if( prefabObject && parentData.node.HasLinkToObjectWithDescriptions( prefabObject.GetHashCode(), linkDescriptions ) ) if( prefabObject && parentData.node.HasLinkToObjectWithDescriptions( prefabObject.GetInstanceID(), linkDescriptions ) )
return false; return false;
} }
} }
@@ -10,7 +10,7 @@ using UnityEditor.SceneManagement;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER #if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif #endif
@@ -190,6 +190,11 @@ namespace AssetUsageDetectorNamespace
// Can't ping assets that are hidden from Project window (e.g. animator states of AnimatorController), ping the main asset at that path instead // Can't ping assets that are hidden from Project window (e.g. animator states of AnimatorController), ping the main asset at that path instead
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) ); pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
} }
else if( !AssetDatabase.IsMainAsset( obj ) && Array.IndexOf( AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( obj ) ), obj ) < 0 )
{
// VFX Graph assets' nodes are serialized as part of the graph but they are invisible in the Project window even though their hideFlags is None (I don't know how)
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
}
} }
} }
@@ -10,23 +10,23 @@ namespace AssetUsageDetectorNamespace
// 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 struct VariableGetterHolder
{ {
public readonly string name; public readonly MemberInfo variable;
public readonly bool isProperty;
public readonly bool isSerializable; public readonly bool isSerializable;
private readonly VariableGetVal getter; private readonly VariableGetVal getter;
public string Name { get { return variable.Name; } }
public bool IsProperty { get { return variable is PropertyInfo; } }
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable ) public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
{ {
name = fieldInfo.Name; this.variable = fieldInfo;
isProperty = false;
this.isSerializable = isSerializable; this.isSerializable = isSerializable;
this.getter = getter; this.getter = getter;
} }
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable ) public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
{ {
name = propertyInfo.Name; this.variable = propertyInfo;
isProperty = true;
this.isSerializable = isSerializable; this.isSerializable = isSerializable;
this.getter = getter; this.getter = getter;
} }
+1 -1
View File
@@ -1,4 +1,4 @@
= Asset Usage Detector = = Asset Usage Detector (v2.4.0) =
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector Online documentation available at: 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.1.0", "version": "2.4.0",
"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",