Compare commits

...

20 Commits

Author SHA1 Message Date
Süleyman Yasir KULA 68f1b2809e - Previous HideInInspector solution wasn't working if a nested variable had HideInInspector, replaced it with a better solution
- Added SerializeReference support
- Added 2020.1 generic types support
- Fixed deprecated warning messages on 2020.1
2020-07-27 14:15:08 +03:00
Süleyman Yasir KULA 6280305a63 - Searching for references of a prefab stage object in newest Unity versions wasn't working, fixed
- Fields marked with HideInInspector (and with SerializeReference, possibly) weren't searched for references when SearchVariablesWithSerializedObject was used, fixed
2020-07-16 22:39:41 +03:00
Süleyman Yasir KULA 5d04e70b7b Added support for new Shader Graph serialization format 2020-07-04 17:34:00 +03:00
Süleyman Yasir KULA 541e33db89 - Added Shader Graph support (will probably stop working after the serialization format changes: https://github.com/Unity-Technologies/Graphics/pull/222)
- Added support for searching the "#include" lines in shader source codes (e.g. to find references to included .cginc files)
- Default Texture/Object variables assigned to Shader and MonoScript assets via Inspector are now included in search
- Split AssetUsageDetector class into multiple C# files so that it is easier to navigate to the desired variables/functions
2020-07-02 12:12:19 +03:00
Süleyman Yasir KULA bc3a8069b4 - Project Settings are now searched for references
- Fixed #20
2020-06-27 00:18:45 +03:00
Süleyman Yasir KULA 98d1f43180 References to "SceneAsset"s are now found (fixes #22) 2020-06-16 18:46:22 +03:00
Süleyman Yasir KULA 7d24aa4939 Update package.json 2020-05-29 21:23:42 +03:00
Süleyman Yasir KULA c16bef45cd - Assembly Definition Files' "Assembly Definition References" are now included in the search
- Refreshing the "Project Window (Assets)" group in search results page wasn't working sometimes, fixed
- Tooltips were hard to see in 2019.3+, fixed
2020-05-29 15:27:21 +03:00
Süleyman Yasir KULA 7b939a2104 no message 2020-05-14 20:05:42 +03:00
Süleyman Yasir KULA ccf3e2f733 Added OpenUPM instructions 2020-05-14 20:04:02 +03:00
Süleyman Yasir KULA c6b1edfd93 no message 2020-04-28 12:36:27 +03:00
Süleyman Yasir KULA 7358b12609 Added Package Manager support 2020-04-28 12:22:48 +03:00
Süleyman Yasir KULA ab539adc54 Added donation link (thank you for using my assets, and a special thanks if you consider donating) 2020-04-09 15:26:37 +03:00
Süleyman Yasir KULA 4909b9c558 Updated Asset Store link 2020-03-03 15:46:26 +03:00
Süleyman Yasir KULA 94381ff7d2 - Added Window-Asset Usage Detector-New Window menu item
- Fixed #19
- Fixed compilation errors when using a SRP
2020-02-15 13:57:08 +03:00
Süleyman Yasir KULA 17d3b33e8e References from one sub-asset to the other were skipped when "Don't search 'Find references of' themselves for references" was enabled (e.g. a reference from a prefab's child A to child B was skipped while searching for B's references), now fixed. 2020-02-08 23:54:48 +03:00
Süleyman Yasir KULA ff193224e9 - Objects animated via Animation and/or Animator components are now searched for references
- NativeArrays are no longer searched for references, iterating over them can throw InvalidOperationException if the collection is disposed. It shouldn't matter since NativeArrays are meant to store only blittable structs which can't have any Object references (+surprisingly, it can reduce the search time substantially in some projects)
- Fixed tooltips getting culled by the AssetUsageDetector window in the search results page
2020-01-23 16:13:08 +03:00
Süleyman Yasir KULA 51abec24d7 Fixed compilation error on 2019.3 2020-01-02 14:09:12 +03:00
Süleyman Yasir KULA a29dc59a75 - Now using GUI instead of GUILayout to draw the search results which results in much better GUI performance
- Fixed a StackOverflowException
2019-11-19 23:07:25 +03:00
Süleyman Yasir KULA 96315ec435 For references found inside enumerators like arrays, reflection algorithm now shows the array index that the reference is found at instead of a generic "(IEnumerable)" 2019-11-10 12:34:51 +03:00
24 changed files with 2691 additions and 1142 deletions
+46
View File
@@ -0,0 +1,46 @@
# Asset Usage Detector for Unity 3D
![screenshot1](screenshots/img1.png)
**Available on Asset Store:** https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837
**Forum Thread:** https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/
**[Support the Developer ☕](https://yasirkula.itch.io/unity3d)**
## ABOUT
This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!
## INSTALLATION
There are 5 ways to install this plugin:
- import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package*
- clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder
- import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837)
- *(via Package Manager)* add the following line to *Packages/manifest.json*:
- `"com.yasirkula.assetusagedetector": "https://github.com/yasirkula/UnityAssetUsageDetector.git",`
- *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command:
- `openupm add com.yasirkula.assetusagedetector`
## HOW TO
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- or, right click an object and select **Search For References**
- In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the references are formed. If a node's label contains text inside square brackets (e.g. *\[Child object\]*), then that text describes how that node is connected to the node to its left
## FEATURES
- You can search for references of any object that extends *UnityEngine.Object*
- Extensive search algorithm that uses *SerializedObject* and *reflection* to find references
- Can search in multiple scenes at once
- Can show complete paths to the references or only the most relevant parts of the paths (see the demonstration below)
![screenshot2](screenshots/img2.gif)
## KNOWN LIMITATIONS
- *static* variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 103 KiB

View File
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 56436d3bf8363484a9696f11a535c2fb
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d2008cf328f1a2e4da790e4bdd4191cd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
{
"name": "AssetUsageDetector.Editor",
"references": [],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8579ab42c9ab63d4bac5fb07bd390b46
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
public partial class AssetUsageDetector
{
#region Helper Classes
private class CacheEntry
{
public enum Result { Unknown = 0, No = 1, Yes = 2 };
public string hash;
public string[] dependencies;
public long[] fileSizes;
public bool verified;
public Result searchResult;
public CacheEntry( string path )
{
Verify( path );
}
public CacheEntry( string hash, string[] dependencies, long[] fileSizes )
{
this.hash = hash;
this.dependencies = dependencies;
this.fileSizes = fileSizes;
}
public void Verify( string path )
{
string hash = AssetDatabase.GetAssetDependencyHash( path ).ToString();
if( this.hash != hash )
{
this.hash = hash;
Refresh( path );
}
verified = true;
}
public void Refresh( string path )
{
dependencies = AssetDatabase.GetDependencies( path, false );
if( fileSizes == null || fileSizes.Length != dependencies.Length )
fileSizes = new long[dependencies.Length];
for( int i = 0; i < dependencies.Length; i++ )
{
FileInfo assetFile = new FileInfo( dependencies[i] );
fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L;
}
}
}
#endregion
// An optimization to fetch the dependencies of an asset only once (key is the path of the asset)
private Dictionary<string, CacheEntry> assetDependencyCache;
private CacheEntry lastRefreshedCacheEntry;
private string CachePath { get { return Application.dataPath + "/../Library/AssetUsageDetector.cache"; } } // Path of the cache file
public void SaveCache()
{
if( assetDependencyCache == null )
return;
try
{
using( FileStream stream = new FileStream( CachePath, FileMode.Create ) )
using( BinaryWriter writer = new BinaryWriter( stream ) )
{
writer.Write( assetDependencyCache.Count );
foreach( var keyValuePair in assetDependencyCache )
{
CacheEntry cacheEntry = keyValuePair.Value;
string[] dependencies = cacheEntry.dependencies;
long[] fileSizes = cacheEntry.fileSizes;
writer.Write( keyValuePair.Key );
writer.Write( cacheEntry.hash );
writer.Write( dependencies.Length );
for( int i = 0; i < dependencies.Length; i++ )
{
writer.Write( dependencies[i] );
writer.Write( fileSizes[i] );
}
}
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
private void LoadCache()
{
if( File.Exists( CachePath ) )
{
using( FileStream stream = new FileStream( CachePath, FileMode.Open, FileAccess.Read ) )
using( BinaryReader reader = new BinaryReader( stream ) )
{
try
{
int cacheSize = reader.ReadInt32();
assetDependencyCache = new Dictionary<string, CacheEntry>( cacheSize );
for( int i = 0; i < cacheSize; i++ )
{
string assetPath = reader.ReadString();
string hash = reader.ReadString();
int dependenciesLength = reader.ReadInt32();
string[] dependencies = new string[dependenciesLength];
long[] fileSizes = new long[dependenciesLength];
for( int j = 0; j < dependenciesLength; j++ )
{
dependencies[j] = reader.ReadString();
fileSizes[j] = reader.ReadInt64();
}
assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies, fileSizes );
}
}
catch( Exception e )
{
assetDependencyCache = null;
Debug.LogWarning( "Couldn't load cache (probably cache format has changed in an update), will regenerate cache.\n" + e.ToString() );
}
}
}
// Generate cache for all assets for the first time
if( assetDependencyCache == null )
{
assetDependencyCache = new Dictionary<string, CacheEntry>( 1024 * 8 );
string[] allAssets = AssetDatabase.GetAllAssetPaths();
if( allAssets.Length > 0 )
{
double startTime = EditorApplication.timeSinceStartup;
try
{
for( int i = 0; i < allAssets.Length; i++ )
{
if( i % 30 == 0 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Generating cache for the first time (optional)", (float) i / allAssets.Length ) )
{
EditorUtility.ClearProgressBar();
Debug.LogWarning( "Initial cache generation cancelled, cache will be generated on the fly as more and more assets are searched." );
break;
}
assetDependencyCache[allAssets[i]] = new CacheEntry( allAssets[i] );
}
EditorUtility.ClearProgressBar();
Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" );
Debug.Log( "You can always reset the cache by deleting " + Path.GetFullPath( CachePath ) );
SaveCache();
}
catch( Exception e )
{
EditorUtility.ClearProgressBar();
Debug.LogException( e );
}
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 71ea9a3fd0b82594d8130d882dbfc844
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 93aaae685d4c3db44baeb91a0296855e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -5,8 +5,12 @@ using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public enum Phase { Setup, Processing, Complete };
@@ -16,6 +20,7 @@ namespace AssetUsageDetectorNamespace.Extras
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
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";
private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
@@ -26,6 +31,9 @@ namespace AssetUsageDetectorNamespace.Extras
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
private const string PREFS_SHOW_TOOLTIPS = "AUD_Tooltips";
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );
private AssetUsageDetector core = new AssetUsageDetector();
private SearchResult searchResult; // Overall search results
@@ -38,7 +46,8 @@ namespace AssetUsageDetectorNamespace.Extras
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 searchInAssetsFolder = true; // Assets in Project window
private bool dontSearchInSourceAssets = false; // objectsToSearch won't be searched for internal references
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
private List<Object> searchInAssetsSubset = new List<Object>() { null }; // If not empty, only these assets are searched for references
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
@@ -66,19 +75,52 @@ namespace AssetUsageDetectorNamespace.Extras
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );
private readonly GUIContent restoreInitialSceneSetupLabel = new GUIContent( "Restore initial scene setup (Recommended)", "For example, if scene A was open when the search was started and scenes A and B are open after the search is completed, clicking the \"Reset Search\" button will automatically close scene B" );
private readonly GUIContent showTooltipsLabel = new GUIContent( "Show tooltips", "Display nodes' contents in a tooltip when cursor hovers over them" );
private Vector2 scrollPosition = Vector2.zero;
private static AssetUsageDetectorWindow visibleWindow = null;
private bool shouldRepositionSelf;
private Rect windowTargetPosition;
private static AssetUsageDetectorWindow mainWindow = null;
// Add "Asset Usage Detector" menu item to the Window menu
[MenuItem( "Window/Asset Usage Detector" )]
private static void Init()
[MenuItem( "Window/Asset Usage Detector/Active Window" )]
private static void OpenActiveWindow()
{
AssetUsageDetectorWindow window = GetWindow<AssetUsageDetectorWindow>();
window.titleContent = new GUIContent( "Asset Usage Detector" );
window.minSize = new Vector2( 325f, 220f );
if( !mainWindow )
{
mainWindow = GetWindow<AssetUsageDetectorWindow>();
mainWindow.titleContent = windowTitle;
mainWindow.minSize = windowMinSize;
}
window.Show();
mainWindow.Show();
}
[MenuItem( "Window/Asset Usage Detector/New Window" )]
private static void OpenNewWindow()
{
Rect? windowTargetPosition = null;
if( mainWindow )
{
Rect position = mainWindow.position;
position.position += new Vector2( 50f, 50f );
windowTargetPosition = position;
}
mainWindow = CreateInstance<AssetUsageDetectorWindow>();
mainWindow.titleContent = windowTitle;
mainWindow.minSize = windowMinSize;
if( windowTargetPosition.HasValue )
{
mainWindow.shouldRepositionSelf = true;
mainWindow.windowTargetPosition = windowTargetPosition.Value;
}
mainWindow.Show( true );
}
// Quickly initiate search for the selected assets
@@ -133,57 +175,59 @@ namespace AssetUsageDetectorNamespace.Extras
private static void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters )
{
if( visibleWindow != null && !visibleWindow.ReturnToSetupPhase( true ) )
if( mainWindow != null && !mainWindow.ReturnToSetupPhase( true ) )
{
Debug.LogError( "Need to reset the previous search first!" );
return;
}
Init();
OpenActiveWindow();
visibleWindow.objectsToSearch.Clear();
mainWindow.objectsToSearch.Clear();
if( searchObjects != null )
{
foreach( Object obj in searchObjects )
visibleWindow.objectsToSearch.Add( new ObjectToSearch( obj ) );
mainWindow.objectsToSearch.Add( new ObjectToSearch( obj ) );
}
if( searchParameters != null )
{
visibleWindow.ParseSceneSearchMode( searchParameters.searchInScenes );
visibleWindow.searchInAssetsFolder = searchParameters.searchInAssetsFolder;
visibleWindow.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
visibleWindow.searchDepthLimit = searchParameters.searchDepthLimit;
visibleWindow.fieldModifiers = searchParameters.fieldModifiers;
visibleWindow.propertyModifiers = searchParameters.propertyModifiers;
visibleWindow.searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
visibleWindow.lazySceneSearch = searchParameters.lazySceneSearch;
visibleWindow.noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
visibleWindow.showDetailedProgressBar = searchParameters.showDetailedProgressBar;
mainWindow.ParseSceneSearchMode( searchParameters.searchInScenes );
mainWindow.searchInAssetsFolder = searchParameters.searchInAssetsFolder;
mainWindow.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
mainWindow.searchInProjectSettings = searchParameters.searchInProjectSettings;
mainWindow.searchDepthLimit = searchParameters.searchDepthLimit;
mainWindow.fieldModifiers = searchParameters.fieldModifiers;
mainWindow.propertyModifiers = searchParameters.propertyModifiers;
mainWindow.searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
mainWindow.lazySceneSearch = searchParameters.lazySceneSearch;
mainWindow.noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
mainWindow.showDetailedProgressBar = searchParameters.showDetailedProgressBar;
visibleWindow.searchInAssetsSubset.Clear();
mainWindow.searchInAssetsSubset.Clear();
if( searchParameters.searchInAssetsSubset != null )
{
foreach( Object obj in searchParameters.searchInAssetsSubset )
visibleWindow.searchInAssetsSubset.Add( obj );
mainWindow.searchInAssetsSubset.Add( obj );
}
visibleWindow.excludedAssets.Clear();
mainWindow.excludedAssets.Clear();
if( searchParameters.excludedAssetsFromSearch != null )
{
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
visibleWindow.excludedAssets.Add( obj );
mainWindow.excludedAssets.Add( obj );
}
visibleWindow.excludedScenes.Clear();
mainWindow.excludedScenes.Clear();
if( searchParameters.excludedScenesFromSearch != null )
{
foreach( Object obj in searchParameters.excludedScenesFromSearch )
visibleWindow.excludedScenes.Add( obj );
mainWindow.excludedScenes.Add( obj );
}
}
visibleWindow.InitiateSearch();
mainWindow.InitiateSearch();
mainWindow.Repaint();
}
private void Awake()
@@ -193,7 +237,22 @@ namespace AssetUsageDetectorNamespace.Extras
private void OnEnable()
{
visibleWindow = this;
mainWindow = this;
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
#endif
}
private void OnDisable()
{
#if UNITY_2018_3_OR_NEWER
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
#endif
if( mainWindow == this )
mainWindow = null;
}
private void OnDestroy()
@@ -208,8 +267,11 @@ namespace AssetUsageDetectorNamespace.Extras
if( EditorUtility.DisplayDialog( "Scenes", "Restore initial scene setup?", "Yes", "Leave it as is" ) )
searchResult.RestoreInitialSceneSetup();
}
}
visibleWindow = null;
private void OnFocus()
{
mainWindow = this;
}
private void SavePrefs()
@@ -217,6 +279,7 @@ namespace AssetUsageDetectorNamespace.Extras
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers );
EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers );
@@ -232,7 +295,8 @@ namespace AssetUsageDetectorNamespace.Extras
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, false );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
// Fetch public, protected and private non-static fields and properties from objects by default
@@ -286,6 +350,12 @@ namespace AssetUsageDetectorNamespace.Extras
nextPlayModeRefreshTime = EditorApplication.timeSinceStartup + PLAY_MODE_REFRESH_INTERVAL; ;
Repaint();
}
if( shouldRepositionSelf )
{
shouldRepositionSelf = false;
position = windowTargetPosition;
}
}
private void OnGUI()
@@ -308,7 +378,7 @@ namespace AssetUsageDetectorNamespace.Extras
// If we are stuck at this phase, then we have encountered an exception
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup (Recommended)", restoreInitialSceneSetup );
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
@@ -320,8 +390,13 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 10 );
Color c = GUI.color;
GUI.color = Color.cyan;
GUILayout.Box( "SEARCH IN", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
if( searchInAssetsFolder )
@@ -339,7 +414,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.EndHorizontal();
}
GUILayout.Space( 10 );
Utilities.DrawSeparatorLine();
if( searchInAllScenes && !EditorApplication.isPlaying )
GUI.enabled = false;
@@ -375,6 +450,10 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.EndVertical();
GUILayout.EndHorizontal();
Utilities.DrawSeparatorLine();
searchInProjectSettings = EditorGUILayout.ToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );
GUILayout.Space( 10 );
//GUILayout.Box( "SEARCH SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
@@ -429,8 +508,12 @@ namespace AssetUsageDetectorNamespace.Extras
//GUILayout.Space( 10 );
GUI.color = Color.cyan;
GUILayout.Box( "SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
lazySceneSearch = EditorGUILayout.ToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
showDetailedProgressBar = EditorGUILayout.ToggleLeft( "Show detailed progress bar (slower search)", showDetailedProgressBar );
@@ -438,11 +521,14 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 10 );
// Don't let the user press the GO button without any valid search location
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder )
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings )
GUI.enabled = false;
if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) )
{
InitiateSearch();
GUIUtility.ExitGUI();
}
}
else if( currentPhase == Phase.Complete )
{
@@ -454,7 +540,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 10 );
GUI.enabled = true;
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup after search is reset (Recommended)", restoreInitialSceneSetup );
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
@@ -502,11 +588,11 @@ namespace AssetUsageDetectorNamespace.Extras
//GUILayout.Space( 10 );
searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( "Show tooltips", searchResultDrawParameters.showTooltips );
searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( showTooltipsLabel, searchResultDrawParameters.showTooltips );
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges );
searchResultDrawParameters.noAssetDatabaseChanges = noAssetDatabaseChanges;
GUILayout.Space( 10 );
Utilities.DrawSeparatorLine();
GUILayout.Label( "Path drawing mode:" );
@@ -514,7 +600,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references (can be slow with too many references)", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full;
GUILayout.EndHorizontal();
@@ -523,7 +609,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant unique parts of the complete paths that start with a UnityEngine.Object", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant parts (that start with a UnityEngine.Object) of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
GUILayout.EndHorizontal();
@@ -532,7 +618,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths that are unique", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest;
GUILayout.EndHorizontal();
@@ -565,25 +651,7 @@ namespace AssetUsageDetectorNamespace.Extras
SavePrefs();
#if UNITY_2018_3_OR_NEWER
// Try replacing prefab stage objects with their corresponding prefab assets
var openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() )
{
GameObject openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStage.prefabAssetPath );
if( openPrefabStagePrefabAsset != null )
{
for( int i = 0; i < objectsToSearch.Count; i++ )
{
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) &&
objectsToSearch[i].obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) objectsToSearch[i].obj ) )
{
GameObject prefabStageObjectSource = ( (GameObject) objectsToSearch[i].obj ).FollowSymmetricHierarchy( openPrefabStagePrefabAsset );
if( prefabStageObjectSource != null )
objectsToSearch[i].obj = prefabStageObjectSource;
}
}
}
}
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
#endif
// Start searching
@@ -596,6 +664,7 @@ namespace AssetUsageDetectorNamespace.Extras
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
searchInProjectSettings = searchInProjectSettings,
//fieldModifiers = fieldModifiers,
//propertyModifiers = propertyModifiers,
//searchDepthLimit = searchDepthLimit,
@@ -609,6 +678,46 @@ namespace AssetUsageDetectorNamespace.Extras
}
}
#if UNITY_2018_3_OR_NEWER
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
{
if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
return;
#if UNITY_2020_1_OR_NEWER
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
#else
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
#endif
if( prefabAsset == null || prefabAsset.Equals( null ) )
return;
for( int i = 0; i < objectsToSearch.Count; i++ )
{
Object obj = objectsToSearch[i].obj;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
if( prefabStageObjectSource != null )
objectsToSearch[i].obj = prefabStageObjectSource;
List<ObjectToSearch.SubAsset> subAssets = objectsToSearch[i].subAssets;
for( int j = 0; j < subAssets.Count; j++ )
{
obj = subAssets[j].subAsset;
if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
{
prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
if( prefabStageObjectSource != null )
subAssets[j].subAsset = prefabStageObjectSource;
}
}
}
}
}
#endif
private bool ReturnToSetupPhase( bool restoreInitialSceneSetup )
{
if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public class EmptyEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
@@ -2,7 +2,7 @@
using UnityEditor;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public abstract class ListDrawer<T>
{
@@ -4,7 +4,7 @@ using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
[Serializable]
public class ObjectToSearch
@@ -56,74 +56,95 @@ namespace AssetUsageDetectorNamespace.Extras
if( target == null || target.Equals( null ) )
return;
if( !target.IsAsset() || !AssetDatabase.IsMainAsset( target ) || target is SceneAsset )
return;
if( includeTarget )
if( !target.IsAsset() )
{
if( !currentSubAssets.Contains( target ) )
GameObject go = target as GameObject;
if( !go || !go.scene.IsValid() )
return;
// If this is a scene object, add its child objects to the sub-assets list
// but don't include them in the search by default
Transform goTransform = go.transform;
Transform[] children = go.GetComponentsInChildren<Transform>();
for( int i = 0; i < children.Length; i++ )
{
subAssets.Add( new SubAsset( target, true ) );
currentSubAssets.Add( target );
if( ReferenceEquals( children[i], goTransform ) )
continue;
subAssets.Add( new SubAsset( children[i].gameObject, false ) );
}
}
else
{
// If asset is a directory, add all of its contents as sub-assets recursively
if( target.IsFolder() )
{
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
if( !AssetDatabase.IsMainAsset( target ) || target is SceneAsset )
return;
}
}
// Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ )
{
Object asset = assets[i];
if( asset == null || asset.Equals( null ) || asset is Component )
continue;
if( currentSubAssets.Contains( asset ) )
continue;
if( asset != target )
if( includeTarget )
{
subAssets.Add( new SubAsset( asset, true ) );
currentSubAssets.Add( asset );
if( !currentSubAssets.Contains( target ) )
{
subAssets.Add( new SubAsset( target, true ) );
currentSubAssets.Add( target );
}
}
else
{
// If asset is a directory, add all of its contents as sub-assets recursively
if( target.IsFolder() )
{
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
return;
}
}
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
// Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ )
{
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
Object asset = assets[i];
if( asset == null || asset.Equals( null ) || asset is Component )
continue;
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
if( currentSubAssets.Contains( asset ) )
continue;
if( asset != target )
{
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
for( int k = 0; k < monoScriptGuids.Length; k++ )
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
subAssets.Add( new SubAsset( asset, true ) );
currentSubAssets.Add( asset );
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
{
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
for( int k = 0; k < monoScriptGuids.Length; k++ )
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
{
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
}
}
}
}
+416 -109
View File
@@ -1,9 +1,9 @@
using AssetUsageDetectorNamespace.Extras;
using System;
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
@@ -15,6 +15,8 @@ namespace AssetUsageDetectorNamespace
public PathDrawingMode pathDrawingMode;
public bool showTooltips;
public bool noAssetDatabaseChanges;
public Rect guiRect;
public bool shouldRefreshEditorWindow;
public string tooltip;
public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips, bool noAssetDatabaseChanges )
@@ -52,13 +54,20 @@ namespace AssetUsageDetectorNamespace
public List<string> linkDescriptions;
}
private bool success;
#pragma warning disable 1692
#pragma warning disable IDE0044
private bool success; // This is not readonly so that it can be serialized
#pragma warning restore IDE0044
#pragma warning restore 1692
private List<SearchResultGroup> result;
private SceneSetup[] initialSceneSetup;
private AssetUsageDetector searchHandler;
private AssetUsageDetector.Parameters m_searchParameters;
private float guiHeight; // Prevents scroll view's position from getting reset at domain reload
private List<SerializableNode> serializedNodes;
private List<SerializableResultGroup> serializedGroups;
@@ -118,6 +127,7 @@ namespace AssetUsageDetectorNamespace
Object[] searchInScenesSubset = m_searchParameters.searchInScenesSubset;
bool searchInAssetsFolder = m_searchParameters.searchInAssetsFolder;
Object[] searchInAssetsSubset = m_searchParameters.searchInAssetsSubset;
bool searchInProjectSettings = m_searchParameters.searchInProjectSettings;
try
{
@@ -125,6 +135,15 @@ namespace AssetUsageDetectorNamespace
{
m_searchParameters.searchInScenes = SceneSearchMode.None;
m_searchParameters.searchInScenesSubset = null;
m_searchParameters.searchInProjectSettings = false;
}
else if( searchResultGroup.Type == SearchResultGroup.GroupType.ProjectSettings )
{
m_searchParameters.searchInScenes = SceneSearchMode.None;
m_searchParameters.searchInScenesSubset = null;
m_searchParameters.searchInAssetsFolder = false;
m_searchParameters.searchInAssetsSubset = null;
m_searchParameters.searchInProjectSettings = true;
}
else if( searchResultGroup.Type == SearchResultGroup.GroupType.Scene )
{
@@ -132,6 +151,7 @@ namespace AssetUsageDetectorNamespace
m_searchParameters.searchInScenesSubset = new Object[1] { AssetDatabase.LoadAssetAtPath<SceneAsset>( searchResultGroup.Title ) };
m_searchParameters.searchInAssetsFolder = false;
m_searchParameters.searchInAssetsSubset = null;
m_searchParameters.searchInProjectSettings = false;
}
else
{
@@ -139,6 +159,7 @@ namespace AssetUsageDetectorNamespace
m_searchParameters.searchInScenesSubset = null;
m_searchParameters.searchInAssetsFolder = false;
m_searchParameters.searchInAssetsSubset = null;
m_searchParameters.searchInProjectSettings = false;
}
m_searchParameters.lazySceneSearch = false;
@@ -147,13 +168,20 @@ namespace AssetUsageDetectorNamespace
// Make sure the AssetDatabase is up-to-date
AssetDatabase.SaveAssets();
List<SearchResultGroup> searchResult = searchHandler.Run( m_searchParameters ).result;
if( searchResult != null )
SearchResult searchResult = searchHandler.Run( m_searchParameters );
if( !searchResult.success )
{
EditorUtility.DisplayDialog( "Error", "Couldn't refresh, check console for more info.", "OK" );
return;
}
List<SearchResultGroup> searchResultGroups = searchResult.result;
if( searchResultGroups != null )
{
int newSearchResultGroupIndex = -1;
for( int i = 0; i < searchResult.Count; i++ )
for( int i = 0; i < searchResultGroups.Count; i++ )
{
if( searchResultGroup.Title == searchResult[i].Title )
if( searchResultGroup.Title == searchResultGroups[i].Title )
{
newSearchResultGroupIndex = i;
break;
@@ -161,7 +189,7 @@ namespace AssetUsageDetectorNamespace
}
if( newSearchResultGroupIndex >= 0 )
result[searchResultGroupIndex] = searchResult[newSearchResultGroupIndex];
result[searchResultGroupIndex] = searchResultGroups[newSearchResultGroupIndex];
else
searchResultGroup.Clear();
}
@@ -172,6 +200,7 @@ namespace AssetUsageDetectorNamespace
m_searchParameters.searchInScenesSubset = searchInScenesSubset;
m_searchParameters.searchInAssetsFolder = searchInAssetsFolder;
m_searchParameters.searchInAssetsSubset = searchInAssetsSubset;
m_searchParameters.searchInProjectSettings = searchInProjectSettings;
}
}
@@ -179,18 +208,55 @@ namespace AssetUsageDetectorNamespace
{
parameters.searchResult = this;
parameters.tooltip = null;
parameters.guiRect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_0 );
float guiInitialY = parameters.guiRect.y;
for( int i = 0; i < result.Count; i++ )
{
result[i].DrawOnGUI( parameters );
if( parameters.tooltip != null )
if( i < result.Count - 1 )
{
Rect rect = parameters.guiRect;
rect.y += 10f;
parameters.guiRect = rect;
}
}
if( Event.current.type == EventType.Repaint )
guiHeight = parameters.guiRect.y - guiInitialY;
// To work nicely with GUILayout and scroll view
EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, GUILayout.Height( guiHeight ) );
if( !string.IsNullOrEmpty( parameters.tooltip ) )
{
// Show tooltip at mouse position
Vector2 mousePos = Event.current.mousePosition;
Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( parameters.tooltip ) );
size.x += 10f;
GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), parameters.tooltip, Utilities.TooltipGUIStyle );
Rect tooltipRect = new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size );
if( tooltipRect.xMin < 0f )
tooltipRect.x -= tooltipRect.xMin;
else if( tooltipRect.xMax > parameters.guiRect.width )
tooltipRect.x -= tooltipRect.xMax - parameters.guiRect.width;
GUI.Box( tooltipRect, parameters.tooltip, Utilities.TooltipGUIStyle );
}
if( parameters.shouldRefreshEditorWindow )
{
parameters.shouldRefreshEditorWindow = false;
EditorWindow focusedWindow = EditorWindow.focusedWindow;
if( focusedWindow != null )
focusedWindow.Repaint();
EditorWindow mouseOverWindow = EditorWindow.mouseOverWindow;
if( mouseOverWindow != null && mouseOverWindow != focusedWindow )
mouseOverWindow.Repaint();
}
}
@@ -270,6 +336,16 @@ namespace AssetUsageDetectorNamespace
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
return false;
for( int i = 0; i < initialSceneSetup.Length; i++ )
{
Scene scene = EditorSceneManager.GetSceneByPath( initialSceneSetup[i].path );
if( !scene.isLoaded )
scene = EditorSceneManager.OpenScene( initialSceneSetup[i].path, initialSceneSetup[i].isLoaded ? OpenSceneMode.Additive : OpenSceneMode.AdditiveWithoutLoading );
if( initialSceneSetup[i].isActive )
EditorSceneManager.SetActiveScene( scene );
}
SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup();
for( int i = 0; i < sceneFinalSetup.Length; i++ )
{
@@ -350,7 +426,7 @@ namespace AssetUsageDetectorNamespace
// Custom class to hold the results for a single scene or Assets folder
public class SearchResultGroup
{
public enum GroupType { Assets = 0, Scene = 1, DontDestroyOnLoad = 2 };
public enum GroupType { Assets = 0, Scene = 1, DontDestroyOnLoad = 2, ProjectSettings = 3 };
// Custom struct to hold a single path to a reference
public struct ReferencePath
@@ -365,6 +441,8 @@ namespace AssetUsageDetectorNamespace
}
}
private const float HEADER_HEIGHT = 40f;
public string Title { get; private set; }
public GroupType Type { get; private set; }
public bool IsExpanded { get; private set; }
@@ -374,6 +452,11 @@ namespace AssetUsageDetectorNamespace
private List<ReferencePath> referencePathsShortUnique;
private List<ReferencePath> referencePathsShortest;
private float calculatedGUIWidth;
private float calculatedGUIHeight;
private PathDrawingMode calculatedGUIMode;
private ReferenceNodeGUI[] guiNodes;
public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } }
@@ -387,6 +470,9 @@ namespace AssetUsageDetectorNamespace
references = new List<ReferenceNode>();
referencePathsShortUnique = null;
referencePathsShortest = null;
calculatedGUIWidth = 0f;
guiNodes = null;
}
// Add a reference to the list
@@ -404,6 +490,10 @@ namespace AssetUsageDetectorNamespace
referencePathsShortUnique.Clear();
if( referencePathsShortest != null )
referencePathsShortest.Clear();
PendingSearch = false;
calculatedGUIWidth = 0f;
guiNodes = null;
}
// Initializes commonly used variables of the nodes
@@ -422,10 +512,24 @@ namespace AssetUsageDetectorNamespace
}
}
for( int i = references.Count - 1; i >= 0; i-- )
{
references[i].VerifyLinksRecursively();
// Some links might be removed during verification
if( references[i].NumberOfOutgoingLinks == 0 )
references.RemoveAtFast( i );
}
if( references.Count == 0 )
return;
List<ReferenceNode> callStack = new List<ReferenceNode>( 8 );
// For simplicity's sake, get rid of root nodes that are already part of another node's hierarchy
for( int i = references.Count - 1; i >= 0; i-- )
{
if( IsRootNodePartOfAnotherRootNode( i ) )
if( IsRootNodePartOfAnotherRootNode( i, callStack ) )
references.RemoveAtFast( i );
}
@@ -443,6 +547,10 @@ namespace AssetUsageDetectorNamespace
if( mainAsset == null || mainAsset.Equals( null ) )
continue;
// We're already calling AssetDatabase.IsMainAsset but just in case...
if( ReferenceEquals( nodeObject, mainAsset ) )
continue;
if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset )
continue;
@@ -452,12 +560,12 @@ namespace AssetUsageDetectorNamespace
references[i] = newRootNode;
// Make sure that the new root node isn't already a part of another node's hierarchy
if( IsRootNodePartOfAnotherRootNode( i ) )
if( IsRootNodePartOfAnotherRootNode( i, callStack ) )
references.RemoveAtFast( i );
}
}
for( int i = references.Count - 1; i >= 0; i-- )
for( int i = 0; i < references.Count; i++ )
references[i].InitializeRecursively();
}
@@ -473,7 +581,7 @@ namespace AssetUsageDetectorNamespace
return false;
}
private bool IsRootNodePartOfAnotherRootNode( int index )
private bool IsRootNodePartOfAnotherRootNode( int index, List<ReferenceNode> callStack )
{
ReferenceNode node = references[index];
for( int i = references.Count - 1; i >= 0; i-- )
@@ -481,7 +589,7 @@ namespace AssetUsageDetectorNamespace
if( index == i )
continue;
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node ) )
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node, callStack ) )
return true;
}
@@ -533,7 +641,7 @@ namespace AssetUsageDetectorNamespace
referencePathsShortUnique = new List<ReferencePath>( 32 );
for( int i = 0; i < references.Count; i++ )
references[i].CalculateShortUniquePaths( referencePathsShortUnique );
references[i].CalculateShortUniquePaths( referencePathsShortUnique, Type == GroupType.Scene || Type == GroupType.DontDestroyOnLoad );
referencePathsShortest = new List<ReferencePath>( referencePathsShortUnique.Count );
for( int i = 0; i < referencePathsShortUnique.Count; i++ )
@@ -565,15 +673,24 @@ namespace AssetUsageDetectorNamespace
// Draw the results found for this container
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
if( Event.current.type == EventType.Repaint && ( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode || parameters.guiRect.width != calculatedGUIWidth ) )
{
GenerateGUINodes( parameters );
parameters.shouldRefreshEditorWindow = true; // A repaint is needed to work nicely with GUILayout
}
Color c = GUI.color;
GUI.color = Color.cyan;
Rect rect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_40 );
Rect rect = parameters.guiRect;
float width = rect.width;
rect.width = 40f;
rect.height = HEADER_HEIGHT;
if( GUI.Button( rect, IsExpanded ? "v" : ">" ) )
{
IsExpanded = !IsExpanded;
parameters.shouldRefreshEditorWindow = true;
GUIUtility.ExitGUI();
}
@@ -581,8 +698,26 @@ namespace AssetUsageDetectorNamespace
rect.width = width - ( parameters.searchResult != null ? 140f : 40f );
if( GUI.Button( rect, Title, Utilities.BoxGUIStyle ) && Type == GroupType.Scene )
{
// If the container (scene, usually) is clicked, highlight it on Project view
AssetDatabase.LoadAssetAtPath<SceneAsset>( Title ).SelectInEditor();
if( Event.current.button != 1 )
{
// If the container (scene, usually) is left clicked, highlight it on Project view
AssetDatabase.LoadAssetAtPath<SceneAsset>( Title ).SelectInEditor();
}
else if( !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 )
{
// Show context menu when SearchResultGroup's header is right clicked
Scene scene = EditorSceneManager.GetSceneByPath( Title );
if( scene.isLoaded )
{
GenericMenu contextMenu = new GenericMenu();
contextMenu.AddItem( new GUIContent( "Close Scene" ), false, () =>
{
if( !scene.isDirty || EditorSceneManager.SaveModifiedScenesIfUserWantsTo( new Scene[1] { scene } ) )
EditorSceneManager.CloseScene( scene, true );
} );
contextMenu.ShowAsContext();
}
}
}
if( parameters.searchResult != null )
@@ -591,66 +726,110 @@ namespace AssetUsageDetectorNamespace
rect.width = 100f;
if( GUI.Button( rect, "Refresh" ) )
{
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
if( Utilities.AreScenesSaved() || ( EditorUtility.DisplayDialog( "Refresh", "Some scene(s) have unsaved changes, they must be saved before the refresh.", "Save Scenes", "Cancel" ) && EditorSceneManager.SaveOpenScenes() ) )
{
parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges );
GUIUtility.ExitGUI();
}
}
}
rect = parameters.guiRect;
rect.y += HEADER_HEIGHT + 5f;
if( IsExpanded )
{
GUI.color = Color.yellow;
if( PendingSearch )
GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
else if( references.Count == 0 )
GUILayout.Box( "No references found...", Utilities.BoxGUIStyle );
else
{
if( parameters.pathDrawingMode == PathDrawingMode.Full )
{
for( int i = 0; i < references.Count; i++ )
{
GUILayout.Space( 5 );
references[i].DrawOnGUIRecursively( parameters, null );
}
}
else
{
if( referencePathsShortUnique == null )
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
for( int i = 0; i < pathsToDraw.Count; i++ )
{
GUILayout.Space( 5 );
GUILayout.BeginHorizontal();
ReferencePath path = pathsToDraw[i];
path.startNode.DrawOnGUI( parameters, null );
ReferenceNode currentNode = path.startNode;
for( int j = 0; j < path.pathLinksToFollow.Length; j++ )
{
ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]];
link.targetNode.DrawOnGUI( parameters, link.description );
currentNode = link.targetNode;
}
GUILayout.EndHorizontal();
}
}
rect.height = 25f;
GUI.Box( rect, "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle );
}
else if( references.Count == 0 )
{
rect.height = 25f;
GUI.Box( rect, "No references found...", Utilities.BoxGUIStyle );
}
else if( guiNodes != null )
{
rect.height = calculatedGUIHeight;
parameters.guiRect = rect;
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i].DrawOnGUI( parameters );
}
rect.y += rect.height;
}
parameters.guiRect = rect;
GUI.color = c;
}
GUILayout.Space( 10 );
private void GenerateGUINodes( SearchResultDrawParameters parameters )
{
float guiRectWidth = parameters.guiRect.width;
if( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode )
{
if( parameters.pathDrawingMode == PathDrawingMode.Full )
{
List<ReferenceNode> stack = new List<ReferenceNode>( 8 );
guiNodes = new ReferenceNodeGUI[references.Count];
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i] = references[i].GenerateGUINodeRecursive( stack, null );
}
else
{
if( referencePathsShortUnique == null )
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
guiNodes = new ReferenceNodeGUI[pathsToDraw.Count];
for( int i = 0; i < guiNodes.Length; i++ )
{
ReferencePath path = pathsToDraw[i];
ReferenceNode currentNode = path.startNode;
ReferenceNodeGUI currentNodeGUI = currentNode.GenerateGUINode( null );
guiNodes[i] = currentNodeGUI;
for( int j = 0; j < path.pathLinksToFollow.Length; j++ )
{
ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]];
currentNodeGUI.links = new ReferenceNodeGUI[1] { link.targetNode.GenerateGUINode( link.description ) };
currentNode = link.targetNode;
currentNodeGUI = currentNodeGUI.links[0];
}
currentNodeGUI.links = new ReferenceNodeGUI[0];
}
}
for( int i = 0; i < guiNodes.Length; i++ )
guiNodes[i].CalculateDepth();
}
calculatedGUIMode = parameters.pathDrawingMode;
calculatedGUIWidth = guiRectWidth;
calculatedGUIHeight = -5f; // will start from -5f + 5f = 0f
for( int i = 0; i < guiNodes.Length; i++ )
{
calculatedGUIHeight += 5f;
guiNodes[i].CalculateHeight( guiRectWidth );
guiNodes[i].CalculateOffset( new Vector2( 0f, calculatedGUIHeight ) );
calculatedGUIHeight += guiNodes[i].size.y;
}
}
// Serialize this result group
@@ -708,12 +887,12 @@ namespace AssetUsageDetectorNamespace
private static int uid_last = 0;
private readonly int uid;
public object nodeObject;
private readonly List<Link> links;
internal object nodeObject;
private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise
private string description; // String to print on this node
private readonly List<Link> links;
public Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } }
public int NumberOfOutgoingLinks { get { return links.Count; } }
@@ -725,11 +904,6 @@ namespace AssetUsageDetectorNamespace
uid = uid_last++;
}
public ReferenceNode( object obj ) : this()
{
nodeObject = obj;
}
// Add a one-way connection to another node
public void AddLinkTo( ReferenceNode nextNode, string description = null )
{
@@ -759,6 +933,40 @@ namespace AssetUsageDetectorNamespace
}
}
public void CopyReferencesTo( ReferenceNode other )
{
other.links.Clear();
other.links.AddRange( links );
}
// Remove any redundant connections that this node has
public void VerifyLinksRecursively()
{
// Make sure that this functions isn't called multiple times per node (avoids StackOverflowException)
if( description != null )
return;
description = "";
for( int i = links.Count - 1; i >= 0; i-- )
{
// Links from a GameObject to its components should be omitted if the component has no references (these are redundant links)
if( links[i].targetNode.links.Count == 0 && nodeObject is GameObject )
{
Component component = links[i].targetNode.nodeObject as Component;
if( component != null && !component.Equals( null ) && component.gameObject == (GameObject) nodeObject )
{
links.RemoveAtFast( i );
continue;
}
}
links[i].targetNode.VerifyLinksRecursively();
}
description = null;
}
// Initialize node's commonly used variables
public void InitializeRecursively()
{
@@ -789,20 +997,29 @@ namespace AssetUsageDetectorNamespace
}
// Returns whether or not specified node is part of this node's siblings
public bool NodeExistsInChildrenRecursive( ReferenceNode node )
public bool NodeExistsInChildrenRecursive( ReferenceNode node, List<ReferenceNode> callStack )
{
if( callStack.ContainsFast( this ) )
return false;
for( int i = 0; i < links.Count; i++ )
{
if( links[i].targetNode == node )
return true;
}
callStack.Add( this );
for( int i = 0; i < links.Count; i++ )
{
if( links[i].targetNode.NodeExistsInChildrenRecursive( node ) )
if( links[i].targetNode.NodeExistsInChildrenRecursive( node, callStack ) )
{
callStack.RemoveAt( callStack.Count - 1 );
return true;
}
}
callStack.RemoveAt( callStack.Count - 1 );
return false;
}
@@ -814,18 +1031,18 @@ namespace AssetUsageDetectorNamespace
}
// Calculate short unique paths that start with this node
public void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> currentPaths )
public void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> currentPaths, bool startPathsWithSceneObjects )
{
CalculateShortUniquePaths( currentPaths, new List<ReferenceNode>( 8 ), new List<int>( 8 ) { -1 }, 0 );
CalculateShortUniquePaths( currentPaths, startPathsWithSceneObjects, new List<ReferenceNode>( 8 ), new List<int>( 8 ) { -1 }, 0, new List<ReferenceNode>( 8 ) );
}
// Just some boring calculations to find the short unique paths recursively
private void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> shortestPaths, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath )
private void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> shortestPaths, bool startPathsWithSceneObjects, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath, List<ReferenceNode> stack )
{
int currentIndex = currentPath.Count;
currentPath.Add( this );
if( links.Count == 0 )
if( links.Count == 0 || stack.ContainsFast( this ) )
{
// Check if the path to the reference is unique (not discovered so far)
bool isUnique = true;
@@ -861,12 +1078,19 @@ namespace AssetUsageDetectorNamespace
else
{
if( instanceId.HasValue ) // nodeObject is Unity object
latestObjectIndexInPath = currentIndex;
{
if( !startPathsWithSceneObjects || !AssetDatabase.Contains( instanceId.Value ) )
latestObjectIndexInPath = currentIndex;
}
for( int i = 0; i < links.Count; i++ )
{
currentPathIndices.Add( i );
links[i].targetNode.CalculateShortUniquePaths( shortestPaths, currentPath, currentPathIndices, latestObjectIndexInPath );
stack.Add( this );
links[i].targetNode.CalculateShortUniquePaths( shortestPaths, startPathsWithSceneObjects, currentPath, currentPathIndices, latestObjectIndexInPath, stack );
stack.RemoveAt( stack.Count - 1 );
currentPathIndices.RemoveAt( currentIndex + 1 );
}
}
@@ -874,41 +1098,33 @@ namespace AssetUsageDetectorNamespace
currentPath.RemoveAt( currentIndex );
}
// Draw all the paths that start with this node on GUI recursively
public void DrawOnGUIRecursively( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
public ReferenceNodeGUI GenerateGUINode( string linkToPrevNodeDescription )
{
GUILayout.BeginHorizontal();
DrawOnGUI( parameters, linkToPrevNodeDescription );
if( links.Count > 0 )
return new ReferenceNodeGUI()
{
GUILayout.BeginVertical();
for( int i = 0; i < links.Count; i++ )
{
ReferenceNode next = links[i].targetNode;
next.DrawOnGUIRecursively( parameters, links[i].description );
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
label = new GUIContent( string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ) ),
instanceId = instanceId
};
}
// Draw only this node on GUI
public void DrawOnGUI( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
public ReferenceNodeGUI GenerateGUINodeRecursive( List<ReferenceNode> stack, string linkToPrevNodeDescription )
{
string label = string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description );
if( GUILayout.Button( label, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_HEIGHT ) )
ReferenceNodeGUI guiNode = GenerateGUINode( linkToPrevNodeDescription );
if( stack.ContainsFast( this ) )
guiNode.links = new ReferenceNodeGUI[0];
else
{
// If a reference is clicked, highlight it (either on Hierarchy view or Project view)
UnityObject.SelectInEditor();
stack.Add( this );
guiNode.links = new ReferenceNodeGUI[links.Count];
for( int i = 0; i < links.Count; i++ )
guiNode.links[i] = links[i].targetNode.GenerateGUINodeRecursive( stack, links[i].description );
stack.RemoveAt( stack.Count - 1 );
}
if( parameters.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) )
parameters.tooltip = label;
return guiNode;
}
// Serialize this node and its connected nodes recursively
@@ -966,4 +1182,95 @@ namespace AssetUsageDetectorNamespace
return uid;
}
}
public class ReferenceNodeGUI
{
public GUIContent label;
public ReferenceNodeGUI[] links;
public int? instanceId;
private int depth;
private Vector2 offset;
public Vector2 size;
public void CalculateDepth()
{
depth = 0;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateDepth();
if( links[i].depth > depth )
depth = links[i].depth;
}
depth++;
}
public void CalculateHeight( float totalWidth )
{
size.x = totalWidth / depth;
totalWidth -= size.x;
size.y = Utilities.BoxGUIStyle.CalcHeight( label, size.x );
float connectedNodesHeight = 0f;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateHeight( totalWidth );
connectedNodesHeight += links[i].size.y;
}
if( size.y < connectedNodesHeight )
size.y = connectedNodesHeight;
else if( size.y > connectedNodesHeight )
ExpandHeightLeftToRight();
}
private void ExpandHeightLeftToRight()
{
float connectedNodesHeight = 0f;
for( int i = 0; i < links.Length; i++ )
connectedNodesHeight += links[i].size.y;
if( size.y > connectedNodesHeight )
{
for( int i = 0; i < links.Length; i++ )
{
links[i].size.y = size.y * links[i].size.y / connectedNodesHeight;
links[i].ExpandHeightLeftToRight();
}
}
}
public void CalculateOffset( Vector2 baseOffset )
{
offset = baseOffset;
baseOffset.x += size.x;
for( int i = 0; i < links.Length; i++ )
{
links[i].CalculateOffset( baseOffset );
baseOffset.y += links[i].size.y;
}
}
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
Rect rect = parameters.guiRect;
rect.position += offset;
rect.size = size;
if( GUI.Button( rect, label, Utilities.BoxGUIStyle ) && instanceId.HasValue )
{
// If a reference is clicked, highlight it (either on Hierarchy view or Project view)
EditorUtility.InstanceIDToObject( instanceId.Value ).SelectInEditor();
}
for( int i = 0; i < links.Length; i++ )
links[i].DrawOnGUI( parameters );
if( parameters.showTooltips && Event.current.type == EventType.Repaint && rect.Contains( Event.current.mousePosition ) )
parameters.tooltip = label.text;
}
}
}
+136 -13
View File
@@ -1,13 +1,21 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
#if UNITY_2018_1_OR_NEWER
using Unity.Collections;
#endif
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public static class Utilities
{
@@ -36,8 +44,15 @@ namespace AssetUsageDetectorNamespace.Extras
#endif
};
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
#if UNITY_2018_1_OR_NEWER
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
#endif
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
private static readonly StringBuilder stringBuilder = new StringBuilder( 10 );
#if UNITY_2018_3_OR_NEWER
private static int previousPingedPrefabInstanceId;
private static double previousPingedPrefabPingTime;
@@ -48,6 +63,8 @@ namespace AssetUsageDetectorNamespace.Extras
public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 );
public static readonly GUILayoutOption GL_WIDTH_100 = GUILayout.Width( 100 );
public static readonly GUILayoutOption GL_WIDTH_250 = GUILayout.Width( 250 );
public static readonly GUILayoutOption GL_HEIGHT_0 = GUILayout.Height( 0 );
public static readonly GUILayoutOption GL_HEIGHT_2 = GUILayout.Height( 2 );
public static readonly GUILayoutOption GL_HEIGHT_30 = GUILayout.Height( 30 );
public static readonly GUILayoutOption GL_HEIGHT_35 = GUILayout.Height( 35 );
public static readonly GUILayoutOption GL_HEIGHT_40 = GUILayout.Height( 40 );
@@ -90,12 +107,13 @@ namespace AssetUsageDetectorNamespace.Extras
normalState = m_tooltipGUIStyle.normal;
normalState.background = null;
normalState.scaledBackgrounds = new Texture2D[0];
normalState.textColor = Color.black;
}
if( normalState.background == null || normalState.background.Equals( null ) )
{
Texture2D backgroundTexture = new Texture2D( 1, 1 );
Texture2D backgroundTexture = new Texture2D( 1, 1 ) { hideFlags = HideFlags.HideAndDontSave };
backgroundTexture.SetPixel( 0, 0, new Color( 0.88f, 0.88f, 0.88f, 0.85f ) );
backgroundTexture.Apply();
@@ -221,22 +239,30 @@ namespace AssetUsageDetectorNamespace.Extras
if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant )
{
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
var openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
// Try to open the prefab stage of pinged prefabs if they are double clicked
if( previousPingedPrefabInstanceId == objTR.GetInstanceID() && EditorApplication.timeSinceStartup - previousPingedPrefabPingTime <= 0.3f &&
#if UNITY_2020_1_OR_NEWER
( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath ) )
#else
( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.prefabAssetPath ) )
#endif
{
AssetDatabase.OpenAsset( objTR.gameObject );
openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
}
previousPingedPrefabInstanceId = objTR.GetInstanceID();
previousPingedPrefabPingTime = EditorApplication.timeSinceStartup;
#if UNITY_2020_1_OR_NEWER
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath )
#else
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath )
#endif
{
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, openPrefabStage.prefabContentsRoot );
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot );
if( prefabStageGO != null )
{
objTR = prefabStageGO.transform;
@@ -267,10 +293,12 @@ namespace AssetUsageDetectorNamespace.Extras
return selection;
}
public static GameObject FollowSymmetricHierarchy( this GameObject go, GameObject symmetricRoot )
// We are passing "go"s root Transform to thisRoot parameter. If we use go.transform.root instead, when we are in prefab mode on
// newer Unity versions, it points to the preview scene at the root of the prefab stage instead of pointing to the actual root of "go"
public static GameObject FollowSymmetricHierarchy( this GameObject go, GameObject thisRoot, GameObject symmetricRoot )
{
Transform target = go.transform;
Transform root1 = target.root;
Transform root1 = thisRoot.transform;
Transform root2 = symmetricRoot.transform;
while( root1 != target )
{
@@ -302,9 +330,17 @@ namespace AssetUsageDetectorNamespace.Extras
// Check if the field is serializable
public static bool IsSerializable( this FieldInfo fieldInfo )
{
// see Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( fieldInfo.IsInitOnly || ( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) &&
!Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) ) )
// See Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( fieldInfo.IsInitOnly )
return false;
#if UNITY_2019_3_OR_NEWER
// SerializeReference makes even System.Object fields serializable
if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) )
return true;
#endif
if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) )
return false;
return IsTypeSerializable( fieldInfo.FieldType );
@@ -335,6 +371,16 @@ namespace AssetUsageDetectorNamespace.Extras
}
else if( type.IsGenericType )
{
// Generic types are allowed on 2020.1 and later
#if UNITY_2020_1_OR_NEWER
if( type.GetGenericTypeDefinition() == typeof( List<> ) )
{
type = type.GetGenericArguments()[0];
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
#else
if( type.GetGenericTypeDefinition() != typeof( List<> ) )
return false;
@@ -342,18 +388,38 @@ namespace AssetUsageDetectorNamespace.Extras
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
#endif
}
#if !UNITY_2020_1_OR_NEWER
if( type.IsGenericType )
return false;
#endif
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
}
// Check if the type is a common Unity type (let's call them primitives)
public static bool IsPrimitiveUnityType( this Type type )
// Check if instances of this type should be searched for references
public static bool IsIgnoredUnityType( this Type type )
{
return type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum;
if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum )
return true;
#if UNITY_2018_1_OR_NEWER
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
if( type.Namespace == nativeCollectionsNamespace )
return true;
#endif
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
return true;
// Searching pointer variables for reference throws ArgumentException
if( type.IsPointer )
return true;
return false;
}
// Get <get> function for a field
@@ -399,6 +465,34 @@ namespace AssetUsageDetectorNamespace.Extras
return true;
}
// Returns file extension in lowercase (period not included)
public static string GetFileExtension( string path )
{
int extensionIndex = path.LastIndexOf( '.' );
if( extensionIndex < 0 || extensionIndex >= path.Length - 1 )
return "";
stringBuilder.Length = 0;
for( extensionIndex++; extensionIndex < path.Length; extensionIndex++ )
{
char ch = path[extensionIndex];
if( ch >= 65 && ch <= 90 ) // A-Z
ch += (char) 32; // Converted to a-z
stringBuilder.Append( ch );
}
return stringBuilder.ToString();
}
// Draw horizontal line inside OnGUI
public static void DrawSeparatorLine()
{
GUILayout.Space( 4 );
GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH );
GUILayout.Space( 4 );
}
// Check if all the objects inside the list are null
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
{
@@ -447,6 +541,35 @@ namespace AssetUsageDetectorNamespace.Extras
return true;
}
// Returns true is str starts with prefix
public static bool StartsWithFast( this string str, string prefix )
{
int aLen = str.Length;
int bLen = prefix.Length;
int ap = 0; int bp = 0;
while( ap < aLen && bp < bLen && str[ap] == prefix[bp] )
{
ap++;
bp++;
}
return bp == bLen;
}
// Returns true is str ends with postfix
public static bool EndsWithFast( this string str, string postfix )
{
int ap = str.Length - 1;
int bp = postfix.Length - 1;
while( ap >= 0 && bp >= 0 && str[ap] == postfix[bp] )
{
ap--;
bp--;
}
return bp < 0;
}
public static bool ContainsFast<T>( this List<T> list, T element )
{
if( !( element is ValueType ) )
@@ -2,7 +2,7 @@
using System.Reflection;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
// Delegate to get the value of a variable (either field or property)
public delegate object VariableGetVal( object obj );
+4
View File
@@ -9,6 +9,10 @@ This tool helps you find usages of the selected asset(s) and/or Object(s) in you
2. HOW TO
Open "Window-Asset Usage Detector" window, configure the settings and hit GO! You can also right click an object and select "Search For References".
In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the
references are formed. If a node's label contains text inside square brackets (e.g. [Child object]), then that text describes how that node is
connected to the node to its left.
3. KNOWN LIMITATIONS
- static variables are not searched
- GUIText materials are not searched
-32
View File
@@ -1,32 +0,0 @@
# Asset Usage Detector for Unity 3D
![screenshot1](screenshots/img1.png)
**Available on Asset Store:** https://www.assetstore.unity3d.com/en/#!/content/112837
**Forum Thread:** https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/
### A. ABOUT
This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!
### B. HOW TO USE
- Import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) to your project
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- or, right click an object and select **Search For References**
### C. FEATURES
- You can search for references of any object that extends *UnityEngine.Object*
- Extensive search algorithm that uses *SerializedObject* and *reflection* to find references
- Can search in multiple scenes at once
- Can show complete paths to the references or only the most relevant parts of the paths (see the demonstration below)
![screenshot2](screenshots/img2.gif)
### D. KNOWN LIMITATIONS
- *static* variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched
+6
View File
@@ -0,0 +1,6 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "1.8.4",
"description": "This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!"
}
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ce102123c0ff0a6429f8d5f930e77d96
PackageManifestImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: