Compare commits

...

35 Commits

Author SHA1 Message Date
yasirkula da921c2e06 "Hide redundant prefab variant links" setting now works as expected, only affecting variables in components and not affecting prefab/MonoScript usages 2023-11-18 17:53:42 +03:00
yasirkula d9cc52cc37 Fixed some properties not being searched in edge cases that may occur when Addressables or VFX Graph packages are present in the project 2023-11-18 17:50:27 +03:00
yasirkula e6641bef48 "Show Root Asset's Name" setting is enabled by default + root asset's name is prepended by "in" word for more clarity 2023-11-18 17:46:28 +03:00
yasirkula a6d91a58a3 Scenes in read-only packages aren't searched since they can't be opened (fixed #36) (closed #37) 2023-11-18 17:45:22 +03:00
yasirkula ace8ac4947 Bumped version 2023-10-07 20:43:03 +03:00
yasirkula 02167c28a2 "Show Children In New Window" window no longer auto-closes when clicked outside 2023-10-07 20:42:53 +03:00
yasirkula 092b80ba29 Fixed some references initially being displayed collapsed after the search 2023-10-07 20:41:10 +03:00
yasirkula 524965aee7 If an exception is thrown while accessing a variable via reflection, a more detailed error message is logged 2023-10-07 20:40:21 +03:00
yasirkula efad9fa158 Muted an exception that is raised while searching "ref struct"s for reference 2023-10-07 20:39:31 +03:00
yasirkula 6cd2b407cc Scene lighting settings are now searched for references (can be turned off) 2023-10-07 20:38:37 +03:00
yasirkula 3c4292159a Fixed deprecated EditorSceneManager warnings on 2022.2+ 2023-08-31 07:10:51 +03:00
yasirkula 1a2eba24bd Added a setting to show sub-assets' root asset names in search results (disabled by default) (closes #35) 2023-06-27 14:02:34 +03:00
yasirkula cf0fea56ab Fixed 3D model assets' direct children not being pinged correctly when selected via a search result 2023-06-27 14:01:20 +03:00
yasirkula 956aea1ced Added GitHub Sponsors link to README 2023-05-31 11:21:14 +03:00
Süleyman Yasir KULA 466a152ba6 Update README.md 2023-05-07 21:49:19 +03:00
yasirkula 5eda0c1cb0 Added VFX Graph support 2023-05-07 21:47:22 +03:00
yasirkula 42e3278129 Fixed not being able to ping some asset search results in Project window (in particular, VFX graph search results) 2023-05-07 21:38:28 +03:00
yasirkula f6a999f053 Fixed an exception that occurs when a VFX Graph window is open and the open VFX Graph asset is searched for references (there may be other similar edge cases, as well) 2023-05-07 21:37:38 +03:00
yasirkula 8441e4701c Addressables support no longer requires manual modifications 2023-05-07 21:36:05 +03:00
yasirkula d57a707678 Fixed exceptions while searching for some URP assets' references due to their overriden GetHashCode functions 2023-03-18 15:12:13 +03:00
yasirkula 3fa3344507 Fixed #33 2023-03-18 15:09:37 +03:00
yasirkula 8072530c2c Added experimental Addressables support (requires manual modifications) (closed #29) 2022-10-15 17:11:42 +03:00
yasirkula 28a73e2843 Shaders are searched for #include_with_pragmas references in addition to #include references 2022-09-23 14:17:52 +03:00
yasirkula c7e52466ef Added Collapse All button to Asset Usage Detector window's context menu that collapses all search result groups at once 2022-09-23 14:16:52 +03:00
yasirkula 875f3e6794 Fixed right clicking Unused Objects group throwing an exception if that search result group hasn't been expanded yet 2022-09-23 14:16:04 +03:00
yasirkula 635d0653fa Material's color and mainTexture properties aren't searched at runtime since they're searched by SearchMaterial anyways and they can actually throw errors in the Console if the corresponding shader property doesn't exist 2022-09-23 14:15:13 +03:00
yasirkula cb4454b493 - Terrains are now searched properly
- Fixed an error on latest Unity versions when clicking the "Reset Search" button
2022-07-23 21:53:11 +03:00
yasirkula dfb8541605 Fixed compiler errors on 2021.2 and later 2022-04-24 15:14:47 +03:00
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 1319 additions and 283 deletions
+30 -3
View File
@@ -8,7 +8,7 @@
**Discord:** https://discord.gg/UJJt549AaV
**[Support the Developer ☕](https://yasirkula.itch.io/unity3d)**
**[GitHub Sponsors ☕](https://github.com/sponsors/yasirkula)**
## ABOUT
@@ -30,17 +30,44 @@ There are 5 ways to install this plugin:
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- 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)
![SearchResults1](Images/SearchResults1Dark.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
- *Addressables* aren't supported
- *static* variables aren't searched
- *Resources.Load* usages can't be found
- *ref struct*s can't be searched
- *GUIText* materials aren't searched
- Textures in *Lens Flares* can't be searched
@@ -1,6 +1,9 @@
{
"name": "AssetUsageDetector.Editor",
"references": [],
"rootNamespace": "",
"references": [
"Unity.Addressables"
],
"includePlatforms": [
"Editor"
],
@@ -10,6 +13,17 @@
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"versionDefines": [
{
"name": "com.unity.addressables",
"expression": "0.0.0",
"define": "ASSET_USAGE_ADDRESSABLES"
},
{
"name": "com.unity.visualeffectgraph",
"expression": "0.0.0",
"define": "ASSET_USAGE_VFX_GRAPH"
}
],
"noEngineReferences": false
}
@@ -10,7 +10,7 @@ using System;
using System.IO;
using System.Text;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -31,6 +31,7 @@ namespace AssetUsageDetectorNamespace
public SceneSearchMode searchInScenes = SceneSearchMode.AllScenes;
public Object[] searchInScenesSubset = null;
public Object[] excludedScenesFromSearch = null;
public bool searchInSceneLightingSettings = true;
public bool searchInAssetsFolder = true;
public Object[] searchInAssetsSubset = null;
public Object[] excludedAssetsFromSearch = null;
@@ -44,7 +45,12 @@ namespace AssetUsageDetectorNamespace
public bool searchUnusedMaterialProperties = true;
public SearchRefactoring searchRefactoring = null;
public bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
public bool addressablesSupport = false;
#endif
public bool calculateUnusedObjects = false;
public bool hideDuplicateRows = true;
public bool hideReduntantPrefabVariantLinks = true;
@@ -53,6 +59,8 @@ namespace AssetUsageDetectorNamespace
}
#endregion
private Parameters searchParameters;
// A set that contains the searched scene object(s), asset(s) and their sub-assets (if any)
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
// Scenes of scene object(s) in objectsToSearchSet
@@ -78,14 +86,9 @@ namespace AssetUsageDetectorNamespace
// 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 int searchDepthLimit; // Depth limit for recursively searching variables of objects
private Object currentSearchedObject;
private int currentDepth;
private bool searchUnusedMaterialProperties;
private bool dontSearchInSourceAssets;
private bool searchingSourceAssets;
private bool isInPlayMode;
@@ -160,12 +163,15 @@ namespace AssetUsageDetectorNamespace
// Get the scenes that are open right now
SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null;
Scene activeScene = EditorSceneManager.GetActiveScene();
// Make sure that the AssetDatabase is up-to-date
AssetDatabase.SaveAssets();
try
{
this.searchParameters = searchParameters;
// Initialize commonly used variables
searchResult = new List<SearchResultGroup>(); // Overall search results
@@ -174,10 +180,6 @@ namespace AssetUsageDetectorNamespace
searchedObjectsCount = 0;
searchStartTime = EditorApplication.timeSinceStartup;
searchDepthLimit = searchParameters.searchDepthLimit;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchedObjects.Clear();
searchedUnityObjects.Clear();
animationClipUniqueBindings.Clear();
@@ -289,10 +291,10 @@ namespace AssetUsageDetectorNamespace
if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes )
{
// Get all open (and loaded) scenes
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
if( scene.IsValid() )
Scene scene = SceneManager.GetSceneAt( i );
if( scene.IsValid() && scene.isLoaded )
scenesToSearch.Add( scene.path );
}
}
@@ -314,23 +316,35 @@ namespace AssetUsageDetectorNamespace
if( isInPlayMode )
{
HashSet<string> openScenes = new HashSet<string>();
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
if( scene.IsValid() )
Scene scene = SceneManager.GetSceneAt( i );
if( scene.IsValid() && scene.isLoaded )
openScenes.Add( scene.path );
}
List<string> skippedScenes = new List<string>( scenesToSearch.Count );
scenesToSearch.RemoveWhere( ( path ) =>
{
if( !openScenes.Contains( path ) )
{
Debug.Log( "Can't search unloaded scenes while in play mode, skipped " + path );
skippedScenes.Add( path );
return true;
}
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
@@ -338,7 +352,7 @@ namespace AssetUsageDetectorNamespace
// Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet )
searchedUnityObjects.Add( obj.GetHashCode(), PopReferenceNode( obj ) );
searchedUnityObjects.Add( obj.GetInstanceID(), PopReferenceNode( obj ) );
// Progressbar values
int searchProgress = 0;
@@ -500,19 +514,30 @@ namespace AssetUsageDetectorNamespace
}
}
// Search scenes for references
foreach( string scenePath in scenesToSearch )
{
if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) )
throw new Exception( "Search aborted" );
// Search scene for references
if( string.IsNullOrEmpty( scenePath ) )
continue;
if( excludedScenesPathsSet.Contains( scenePath ) )
continue;
SearchScene( scenePath, searchResult, searchParameters.lazySceneSearch, initialSceneSetup );
#if UNITY_2019_2_OR_NEWER
// Skip scenes in read-only packages (Issue #36)
// Credit: https://forum.unity.com/threads/check-if-asset-inside-package-is-readonly.900902/#post-5990822
if( !scenePath.StartsWithFast( "Assets/" ) )
{
var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath( scenePath );
if( packageInfo != null && packageInfo.source != UnityEditor.PackageManager.PackageSource.Embedded && packageInfo.source != UnityEditor.PackageManager.PackageSource.Local )
continue;
}
#endif
SearchScene( scenePath, searchResult, searchParameters, initialSceneSetup );
}
}
@@ -533,7 +558,7 @@ namespace AssetUsageDetectorNamespace
}
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
if( !dontSearchInSourceAssets )
if( !searchParameters.dontSearchInSourceAssets )
{
searchingSourceAssets = true;
@@ -595,6 +620,10 @@ namespace AssetUsageDetectorNamespace
EditorUtility.ClearProgressBar();
// If the active scene was changed during search, reset it
if( EditorSceneManager.GetActiveScene() != activeScene )
EditorSceneManager.SetActiveScene( activeScene );
#if UNITY_2018_3_OR_NEWER
// If a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed
if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) )
@@ -660,7 +689,7 @@ namespace AssetUsageDetectorNamespace
else
{
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent )
usedObjectPathsSet.Add( parent.gameObject.GetHashCode().ToString() );
usedObjectPathsSet.Add( parent.gameObject.GetInstanceID().ToString() );
}
}
}
@@ -727,13 +756,13 @@ namespace AssetUsageDetectorNamespace
if( !searchedTopmostGameObject )
{
if( obj is GameObject )
unusedMainObjectNodes[obj.GetHashCode().ToString()] = node;
unusedMainObjectNodes[obj.GetInstanceID().ToString()] = node;
else
currentSearchResultGroup.AddReference( node );
}
else // List child GameObject scene objects under their parent GameObject
{
string dictionaryKey = searchedTopmostGameObject.GetHashCode().ToString();
string dictionaryKey = searchedTopmostGameObject.GetInstanceID().ToString();
List<ReferenceNode> unusedSubObjectNodesAtPath;
if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) )
unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
@@ -821,7 +850,7 @@ namespace AssetUsageDetectorNamespace
if( !string.IsNullOrEmpty( assetPath ) )
{
assetsToSearchPathsSet.Add( assetPath );
if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
if( searchParameters.dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
excludedAssetsPathsSet.Add( assetPath );
}
@@ -883,7 +912,7 @@ namespace AssetUsageDetectorNamespace
}
// Search a scene for references
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, bool lazySearch, SceneSetup[] initialSceneSetup )
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, Parameters searchParameters, SceneSetup[] initialSceneSetup )
{
Scene scene = EditorSceneManager.GetSceneByPath( scenePath );
if( isInPlayMode && !scene.isLoaded )
@@ -899,7 +928,7 @@ namespace AssetUsageDetectorNamespace
if( !scene.isLoaded )
{
if( lazySearch )
if( searchParameters.lazySceneSearch )
{
searchResult.Add( new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene, true, true ) );
return;
@@ -915,6 +944,16 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < rootGameObjects.Length; i++ )
SearchGameObjectRecursively( rootGameObjects[i] );
// Search through Lighting Settings (it requires changing the active scene but don't do that in play mode)
if( searchParameters.searchInSceneLightingSettings && ( !isInPlayMode || SceneManager.GetActiveScene() == scene ) )
{
if( !isInPlayMode && EditorSceneManager.GetActiveScene() != scene )
EditorSceneManager.SetActiveScene( scene );
BeginSearchObject( lightmapSettingsGetter() );
BeginSearchObject( renderSettingsGetter() );
}
// If no references are found in the scene and if the scene is not part of the initial scene setup, close it
if( currentSearchResultGroup.NumberOfReferences == 0 )
{
@@ -973,9 +1012,13 @@ namespace AssetUsageDetectorNamespace
if( obj == null || obj.Equals( null ) )
return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack
if( callStack.ContainsFast( obj ) )
return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack (initially, I was using callStack.ContainsFast
// here but it returned false for objects that do exist in the call stack if VFX Graph window was open)
for( int i = callStack.Count - 1; i >= 0; i-- )
{
if( callStack[i].Equals( obj ) )
return null;
}
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
@@ -1000,14 +1043,14 @@ namespace AssetUsageDetectorNamespace
{
if( assetsToSearchSet.Count == 0 )
{
searchedUnityObjects.Add( unityObject.GetHashCode(), null );
searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null;
}
assetPath = AssetDatabase.GetAssetPath( unityObject );
if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) )
{
searchedUnityObjects.Add( unityObject.GetHashCode(), null );
searchedUnityObjects.Add( unityObject.GetInstanceID(), null );
return null;
}
}
@@ -1015,7 +1058,7 @@ namespace AssetUsageDetectorNamespace
callStack.Add( unityObject );
// Search the Object in detail
Func<Object, ReferenceNode> searchFunction;
Func<object, ReferenceNode> searchFunction;
if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) )
result = searchFunction( unityObject );
else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) )
@@ -1050,7 +1093,7 @@ namespace AssetUsageDetectorNamespace
else
{
// Comply with the recursive search limit
if( currentDepth >= searchDepthLimit )
if( currentDepth >= searchParameters.searchDepthLimit )
return null;
callStack.Add( obj );
@@ -1077,13 +1120,13 @@ namespace AssetUsageDetectorNamespace
if( !searchingSourceAsset )
{
if( obj is Object )
searchedUnityObjects.Add( unityObject.GetHashCode(), result );
searchedUnityObjects.Add( unityObject.GetInstanceID(), result );
else
searchedObjects.Add( GetNodeObjectHash( obj ), result );
}
else if( result != null )
{
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetHashCode()] );
result.CopyReferencesTo( searchedUnityObjects[unityObject.GetInstanceID()] );
PoolReferenceNode( result );
}
}
@@ -1094,6 +1137,11 @@ namespace AssetUsageDetectorNamespace
// Check if the asset at specified path depends on any of the references
private bool AssetHasAnyReference( string assetPath )
{
#if ASSET_USAGE_ADDRESSABLES
if( searchParameters.addressablesSupport )
return true;
#endif
if( assetsToSearchPathsSet.Contains( assetPath ) )
return true;
@@ -1212,7 +1260,7 @@ namespace AssetUsageDetectorNamespace
{
if( nodeObject is Object )
{
if( searchedUnityObjects.TryGetValue( nodeObject.GetHashCode(), out referenceNode ) )
if( searchedUnityObjects.TryGetValue( ( (Object) nodeObject ).GetInstanceID(), out referenceNode ) )
return true;
}
else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) )
@@ -1228,7 +1276,7 @@ namespace AssetUsageDetectorNamespace
ReferenceNode result;
if( nodeObject is Object )
{
int hash = nodeObject.GetHashCode();
int hash = ( (Object) nodeObject ).GetInstanceID();
if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null )
{
result = PopReferenceNode( nodeObject );
File diff suppressed because it is too large Load Diff
@@ -96,6 +96,13 @@ namespace AssetUsageDetectorNamespace
#endregion
#region Other Settings
private static bool? m_showRootAssetName = null;
public static bool ShowRootAssetName
{
get { if( m_showRootAssetName == null ) m_showRootAssetName = EditorPrefs.GetBool( "AUD_ShowRootAssetName", true ); return m_showRootAssetName.Value; }
set { if( m_showRootAssetName == value ) return; m_showRootAssetName = value; EditorPrefs.SetBool( "AUD_ShowRootAssetName", value ); }
}
private static bool? m_pingClickedObjects = null;
public static bool PingClickedObjects
{
@@ -171,11 +178,17 @@ namespace AssetUsageDetectorNamespace
public static void PreferencesGUI()
{
float labelWidth = EditorGUIUtility.labelWidth;
#if UNITY_2018_3_OR_NEWER
EditorGUIUtility.labelWidth += 60f;
#else
EditorGUIUtility.labelWidth += 20f;
#endif
EditorGUI.BeginChangeCheck();
SettingsHeaderColor = ColorField( "Settings Header Color", SettingsHeaderColor, Color.cyan );
EditorGUIUtility.labelWidth += 140f;
ShowRootAssetName = EditorGUILayout.Toggle( "Show Root Asset's Name For Sub-Assets (Requires Refresh)", ShowRootAssetName );
EditorGUIUtility.labelWidth -= 140f;
EditorGUILayout.Space();
@@ -198,6 +211,7 @@ namespace AssetUsageDetectorNamespace
EditorGUILayout.Space();
SettingsHeaderColor = ColorField( "Settings Header Color", SettingsHeaderColor, Color.cyan );
SearchResultGroupHeaderColor = ColorField( "Group Header Color", SearchResultGroupHeaderColor, Color.cyan );
RootRowsBackgroundColor = ColorField( "Root Rows Background Color", RootRowsBackgroundColor, EditorGUIUtility.isProSkin ? new Color( 0f, 1f, 1f, 0.15f ) : new Color( 0f, 1f, 1f, 0.25f ) );
RootRowsBorderColor = ColorField( "Root Rows Border Color", RootRowsBorderColor, EditorGUIUtility.isProSkin ? new Color( 0.15f, 0.15f, 0.15f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) );
@@ -5,7 +5,10 @@ using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -19,6 +22,7 @@ namespace AssetUsageDetectorNamespace
private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew };
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
private const string PREFS_SEARCH_SCENE_LIGHTING_SETTINGS = "AUD_LightingSettingsSearch";
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
@@ -28,6 +32,7 @@ namespace AssetUsageDetectorNamespace
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks";
@@ -46,6 +51,8 @@ namespace AssetUsageDetectorNamespace
// This isn't readonly so that it can be serialized
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 IsLocked
{
@@ -59,6 +66,7 @@ namespace AssetUsageDetectorNamespace
}
}
}
#pragma warning restore 0649
private Phase currentPhase = Phase.Setup;
@@ -66,6 +74,7 @@ namespace AssetUsageDetectorNamespace
private bool searchInScenesInBuild = true; // Scenes in build
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
private bool searchInSceneLightingSettings = true; // Window-Rendering-Lighting settings
private bool searchInAssetsFolder = true; // Assets in Project window
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
@@ -77,6 +86,9 @@ namespace AssetUsageDetectorNamespace
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
private bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
private bool addressablesSupport = false;
#endif
private bool searchNonSerializableVariables = true;
private bool searchUnusedMaterialProperties = true;
private bool calculateUnusedObjects = false;
@@ -87,6 +99,8 @@ namespace AssetUsageDetectorNamespace
private BindingFlags fieldModifiers, propertyModifiers;
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
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 );
@@ -144,6 +158,14 @@ namespace AssetUsageDetectorNamespace
objectsToSearch[i].RefreshSubAssets();
} );
}
else if( currentPhase == Phase.Complete )
{
if( searchResult != null && searchResult.NumberOfGroups > 0 )
{
contextMenu.AddSeparator( "" );
contextMenu.AddItem( new GUIContent( "Collapse All" ), false, searchResult.CollapseAllSearchResultGroups );
}
}
}
// Shows lock button at the top-right corner
@@ -166,6 +188,8 @@ namespace AssetUsageDetectorNamespace
if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
{
window.Show();
window.Focus();
return window;
}
@@ -188,6 +212,8 @@ namespace AssetUsageDetectorNamespace
}
window.Show( true );
window.Focus();
return window;
}
@@ -289,6 +315,7 @@ namespace AssetUsageDetectorNamespace
if( searchParameters != null )
{
ParseSceneSearchMode( searchParameters.searchInScenes );
searchInSceneLightingSettings = searchParameters.searchInSceneLightingSettings;
searchInAssetsFolder = searchParameters.searchInAssetsFolder;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchInProjectSettings = searchParameters.searchInProjectSettings;
@@ -297,7 +324,11 @@ namespace AssetUsageDetectorNamespace
propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch;
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = searchParameters.addressablesSupport;
#endif
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows;
hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks;
@@ -368,6 +399,7 @@ namespace AssetUsageDetectorNamespace
private void SavePrefs()
{
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
EditorPrefs.SetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, searchInSceneLightingSettings );
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
@@ -377,6 +409,9 @@ namespace AssetUsageDetectorNamespace
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
EditorPrefs.SetBool( PREFS_ADDRESSABLES_SUPPORT, addressablesSupport );
#endif
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks );
@@ -386,7 +421,7 @@ namespace AssetUsageDetectorNamespace
private void LoadPrefs()
{
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInSceneLightingSettings = EditorPrefs.GetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, true );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
@@ -396,6 +431,9 @@ namespace AssetUsageDetectorNamespace
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
#if ASSET_USAGE_ADDRESSABLES
addressablesSupport = EditorPrefs.GetBool( PREFS_ADDRESSABLES_SUPPORT, false );
#endif
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true );
@@ -448,7 +486,10 @@ namespace AssetUsageDetectorNamespace
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
}
else if( currentPhase == Phase.Setup )
{
@@ -517,6 +558,10 @@ namespace AssetUsageDetectorNamespace
GUILayout.EndVertical();
GUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup( !searchInOpenScenes && !searchInScenesInBuild && !searchInAllScenes );
searchInSceneLightingSettings = WordWrappingToggleLeft( "Scene Lighting Settings (WARNING: This may change the active scene during search)", searchInSceneLightingSettings );
EditorGUI.EndDisabledGroup();
Utilities.DrawSeparatorLine();
searchInProjectSettings = WordWrappingToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );
@@ -527,7 +572,14 @@ namespace AssetUsageDetectorNamespace
GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
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 );
#if ASSET_USAGE_ADDRESSABLES
EditorGUI.EndDisabledGroup();
addressablesSupport = WordWrappingToggleLeft( "Addressables support (Experimental) (WARNING: 'Lazy scene search' will be disabled) (slower search)", addressablesSupport );
#endif
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
#if UNITY_2018_3_OR_NEWER
@@ -563,7 +615,10 @@ namespace AssetUsageDetectorNamespace
GUI.enabled = true;
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
if( searchResult == null )
{
@@ -648,6 +703,7 @@ namespace AssetUsageDetectorNamespace
{
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
searchInScenes = GetSceneSearchMode( true ),
searchInSceneLightingSettings = searchInSceneLightingSettings,
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
@@ -659,7 +715,13 @@ namespace AssetUsageDetectorNamespace
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
#if ASSET_USAGE_ADDRESSABLES
lazySceneSearch = lazySceneSearch && !addressablesSupport,
addressablesSupport = addressablesSupport,
#else
lazySceneSearch = lazySceneSearch,
#endif
calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows,
hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks,
@@ -669,6 +731,9 @@ namespace AssetUsageDetectorNamespace
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 )
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:
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
@@ -371,9 +372,15 @@ namespace AssetUsageDetectorNamespace
return scrollPosition;
}
public int IndexOf( SearchResultGroup searchResult )
public int IndexOf( SearchResultGroup searchResultGroup )
{
return result.IndexOf( searchResult );
return result.IndexOf( searchResultGroup );
}
public void CollapseAllSearchResultGroups()
{
for( int i = 0; i < result.Count; i++ )
result[i].Collapse();
}
public void CancelDelayedTreeViewTooltip()
@@ -600,6 +607,11 @@ namespace AssetUsageDetectorNamespace
treeViewSearchField = null;
}
public void Collapse()
{
IsExpanded = false;
}
// Initializes commonly used variables of the nodes
public void InitializeNodes( HashSet<Object> objectsToSearchSet )
{
@@ -725,7 +737,7 @@ namespace AssetUsageDetectorNamespace
if( searchResult != null )
contextMenu.AddItem( new GUIContent( "Hide" ), false, () => searchResult.RemoveSearchResultGroup( this ) );
if( references.Count > 0 )
if( references.Count > 0 && treeView != null )
{
if( contextMenu.GetItemCount() > 0 )
contextMenu.AddSeparator( "" );
@@ -791,7 +803,12 @@ namespace AssetUsageDetectorNamespace
}
}
if( Type == GroupType.Scene && !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 )
#if UNITY_2022_2_OR_NEWER
int loadedSceneCount = SceneManager.loadedSceneCount;
#else
int loadedSceneCount = EditorSceneManager.loadedSceneCount;
#endif
if( Type == GroupType.Scene && !EditorApplication.isPlaying && loadedSceneCount > 1 )
{
// Show context menu when SearchResultGroup's header is right clicked
Scene scene = EditorSceneManager.GetSceneByPath( ScenePath );
@@ -1163,30 +1180,6 @@ namespace AssetUsageDetectorNamespace
}
}
internal bool HasLinkToObjectWithDescriptions( int instanceId, List<string> descriptions )
{
for( int i = links.Count - 1; i >= 0; i-- )
{
Link link = links[i];
if( link.targetNode.instanceId == instanceId )
{
List<string> _descriptions = link.descriptions;
if( _descriptions.Count != descriptions.Count )
return false;
for( int j = _descriptions.Count - 1; j >= 0; j-- )
{
if( _descriptions[j] != descriptions[j] )
return false;
}
return true;
}
}
return false;
}
public void CopyReferencesTo( ReferenceNode other )
{
other.links.Clear();
@@ -1210,6 +1203,13 @@ namespace AssetUsageDetectorNamespace
{
instanceId = unityObject.GetInstanceID();
Label = unityObject.name + " (" + unityObject.GetType().Name + ")";
if( AssetUsageDetectorSettings.ShowRootAssetName && unityObject.IsAsset() && !AssetDatabase.IsMainAsset( unityObject ) )
{
string mainAssetName = Path.GetFileNameWithoutExtension( AssetDatabase.GetAssetPath( unityObject ) );
if( unityObject.name != mainAssetName )
Label += " <in " + mainAssetName + ">";
}
}
else if( nodeObject != null )
{
@@ -5,7 +5,10 @@ using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -284,25 +287,6 @@ namespace AssetUsageDetectorNamespace
private bool GenerateRowsRecursive( TreeViewItem parent, ReferenceNode referenceNode, ReferenceNodeData parentData, int siblingIndex, int depth, bool? itemForcedVisibility, List<ReferenceNode> stack, HashSet<ReferenceNode> processedNodes, ref int id )
{
#if UNITY_2018_3_OR_NEWER
// If the same reference is found in both a prefab variant and its base prefab, omit the prefab variant to reduce the number of
// redundant links (changing the value in base prefab will automatically change the value in its variants, after all)
if( hideReduntantPrefabVariantLinks && depth > 0 )
{
Object unityObject = referenceNode.UnityObject;
if( unityObject && ( unityObject is Component || unityObject is GameObject ) && unityObject.IsAsset() )
{
List<string> linkDescriptions = parentData.node[siblingIndex].descriptions;
if( linkDescriptions.Count > 0 )
{
Object prefabObject = PrefabUtility.GetCorrespondingObjectFromSource( unityObject );
if( prefabObject && parentData.node.HasLinkToObjectWithDescriptions( prefabObject.GetHashCode(), linkDescriptions ) )
return false;
}
}
}
#endif
TreeViewItem item = new TreeViewItem( id++, depth, "" );
ReferenceNodeData data = new ReferenceNodeData( item, referenceNode, parentData, siblingIndex );
@@ -963,6 +947,8 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < item.children.Count; i++ )
shouldExpand |= GetMainReferenceIdsRecursive( item.children[i], ids );
}
else
shouldExpand = true; // No main reference is encountered in this branch; expand the whole branch
if( shouldExpand )
ids.Add( item.id );
@@ -1175,7 +1161,7 @@ namespace AssetUsageDetectorNamespace
SearchResultTreeView isolatedTreeView = new SearchResultTreeView( new SearchResultTreeViewState(), selectedNodes, TreeType.IsolatedView, null, hideDuplicateRows, hideReduntantPrefabVariantLinks, false );
isolatedTreeView.ExpandMainReferences();
SearchResultTreeViewIsolatedView.Show( new Vector2( EditorWindow.focusedWindow.position.width, isolatedTreeView.totalHeight + 1f ), isolatedTreeView, new GUIContent( selectedNodes[0].Label + ( selectedNodes.Count <= 1 ? "" : ( " (and " + ( selectedNodes.Count - 1 ) + " more)" ) ) ) );
SearchResultTreeViewIsolatedView.Show( new Vector2( EditorWindow.focusedWindow.position.width, Mathf.Max( isolatedTreeView.totalHeight, EditorGUIUtility.singleLineHeight * 5f ) + 1f ), isolatedTreeView, new GUIContent( selectedNodes[0].Label + ( selectedNodes.Count <= 1 ? "" : ( " (and " + ( selectedNodes.Count - 1 ) + " more)" ) ) ) );
}
}
@@ -1329,7 +1315,7 @@ namespace AssetUsageDetectorNamespace
SearchResultTreeViewIsolatedView window = CreateInstance<SearchResultTreeViewIsolatedView>();
window.treeView = treeView;
window.titleContent = title;
window.ShowAuxWindow();
window.Show();
window.minSize = new Vector2( 150f, Mathf.Min( preferredSize.y, EditorGUIUtility.singleLineHeight * 2f ) );
window.position = new Rect( new Vector2( -9999f, -9999f ), preferredSize );
+14 -3
View File
@@ -10,7 +10,7 @@ using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -177,6 +177,12 @@ namespace AssetUsageDetectorNamespace
selection = objTR.gameObject;
#endif
}
else if( prefabAssetType == PrefabAssetType.Model )
{
objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
}
#else
Transform objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
@@ -190,6 +196,11 @@ namespace AssetUsageDetectorNamespace
// Can't ping assets that are hidden from Project window (e.g. animator states of AnimatorController), ping the main asset at that path instead
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
}
else if( !AssetDatabase.IsMainAsset( obj ) && Array.IndexOf( AssetDatabase.LoadAllAssetRepresentationsAtPath( AssetDatabase.GetAssetPath( obj ) ), obj ) < 0 )
{
// VFX Graph assets' nodes are serialized as part of the graph but they are invisible in the Project window even though their hideFlags is None (I don't know how)
pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) );
}
}
}
@@ -405,9 +416,9 @@ namespace AssetUsageDetectorNamespace
// Check if all open scenes are saved (not dirty)
public static bool AreScenesSaved()
{
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
for( int i = 0; i < SceneManager.sceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
Scene scene = SceneManager.GetSceneAt( i );
if( scene.isDirty || string.IsNullOrEmpty( scene.path ) )
return false;
}
@@ -1,5 +1,6 @@
using System;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace AssetUsageDetectorNamespace
@@ -10,23 +11,23 @@ namespace AssetUsageDetectorNamespace
// Custom struct to hold a variable, its important properties and its getter function
public struct VariableGetterHolder
{
public readonly string name;
public readonly bool isProperty;
public readonly MemberInfo variable;
public readonly bool isSerializable;
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 )
{
name = fieldInfo.Name;
isProperty = false;
this.variable = fieldInfo;
this.isSerializable = isSerializable;
this.getter = getter;
}
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
{
name = propertyInfo.Name;
isProperty = true;
this.variable = propertyInfo;
this.isSerializable = isSerializable;
this.getter = getter;
}
@@ -39,7 +40,12 @@ namespace AssetUsageDetectorNamespace
}
catch( Exception e )
{
Debug.LogException( e );
StringBuilder sb = Utilities.stringBuilder;
sb.Length = 0;
sb.Append( "Error while getting the value of (" ).Append( IsProperty ? ( (PropertyInfo) variable ).PropertyType : ( (FieldInfo) variable ).FieldType ).Append( ") " )
.Append( variable.DeclaringType ).Append( "." ).Append( Name ).Append( ": " ).Append( e );
Debug.LogError( sb.ToString() );
return null;
}
}
+3 -44
View File
@@ -1,45 +1,4 @@
= Asset Usage Detector =
= Asset Usage Detector (v2.5.1) =
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
### ABOUT
This tool helps you find usages of the selected asset(s) and/or scene object(s), i.e. lists the objects that refer to them.
### HOW TO
- Open "Window-Asset Usage Detector" window, configure the settings and hit "GO!". You can also right click an object and select "Search For References"
- Asset Usage Detector window can be locked via the "Lock" button in its context menu (or via the lock icon at the top-right corner). If all the
open windows are locked, "Search For References" opens a new window
- Seach results are split into different groups (scenes, assets, Project Settings) and each group displays its search results in its own tree view.
Tree views support multi-selection and keyboard navigation. It's possible to hide groups or rows via their context menu (right click)
- Each root row in a group's tree view represents a different searched object and is drawn with an outline. Usage(s) of a searched object are listed under it as
child rows (with indentation). If a child row's label contains bold text inside square brackets (e.g. "[Variable: m_Shader]"), then that text describes how
its parent row is connected to that row (i.e. the value assigned to the m_Shader variable of that row is its parent row). Child rows can have their own children
as some references involve multiple steps (e.g. when a Texture reference is found in a material which is used in a prefab which is referenced by a scene object)
- Rows with green tint to their left are the main references. For example, main references in a scene are the GameObjects that belong to that scene
- Rows with yellow tint are the parent rows of the selected row(s). To see a row's connection to the searched object, the yellow tinted rows can be traversed
from bottom to top (or, you can hover the cursor over a row and see its connection to the searched object in a tooltip)
- Rows with gradient blue tint are the other occurrences of the selected row(s) (a row can appear multiple times in the tree view, right clicking the row and
selecting "Expand All Occurrences" will reveal them all)
- When "Hide duplicate rows" option is enabled and a row's label starts with "[D]", then it means that the row has appeared in the tree view before and its children
were omitted to simplify the search results (because otherwise the same child rows would be displayed for each occurrence of that row). Only the first occurrence
of a row will display its children when "Hide duplicate rows" is enabled. To find a row's first occurrence, you can right click it and select "Select First Occurrence"
- Inside "Unused Objects" group, if a row's label starts with "[!]", then it means that some of its children are used in the project and it isn't safe to delete
that object. Right clicking the row and selecting "Show Used Children" will reveal the used children
- When a prefab's row is double clicked, that prefab is automatically opened in Prefab Mode
- Selections in tree views are completely independent from each other, it isn't possible to multi-select objects in different tree views. Likewise, selected rows in
a tree view won't be highlighted in other tree views. "Hide duplicate rows" also works independently for each tree view
- You can tweak most settings/colors via "Project Settings/yasirkula/Asset Usage Detector" page (on older versions, this menu is located at "Preferences" window)
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "2.1.0",
"version": "2.5.1",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",