Compare commits

...

109 Commits

Author SHA1 Message Date
yasirkula 790a508dcd Fixed GetScreenFittedRect not working on Unity 2022.3.62+, 6.0.49+ and 6.1.0+ 2025-06-01 17:55:42 +03:00
yasirkula d6a03aa8f2 readonly struct optimization 2025-06-01 17:55:12 +03:00
yasirkula 177db66fbd Simplified Package Manager installation instruction 2025-05-30 10:25:36 +03:00
yasirkula 4415d4b6f4 Updated Unity version to 2021.3.41f1 (simplified codebase accordingly) 2025-05-19 21:14:29 +03:00
arkms 5104901c5d Searching for usages of SpriteAtlas will now include its Sprites, as well (#43) 2025-05-19 20:08:46 +03:00
yasirkula 962f6e04d4 Changed "Hide non-overridden prefab variables" options to "Hide redundant prefab references" which now also apply to C# scripts' and prefab assets' usages (#42) 2024-12-10 19:58:09 +03:00
yasirkula 204de979ba SearchResultGroup's "Hide Search Results" context menu button automatically exits the search 2024-12-10 19:13:58 +03:00
yasirkula 50ce6f56c9 Tiny fix for a switch-case that couldn't be properly auto indentated 2024-12-10 19:05:58 +03:00
yasirkula 0f872ef04d Fix for a tiny warning 2024-12-10 19:04:28 +03:00
yasirkula f68c8a1375 Added AssetUsageDetectorWindow.BeginIndentedGUI and EndIndentedGUI functions to reduce duplicate OnGUI code 2024-12-10 19:04:04 +03:00
yasirkula ecfb1adf88 Added Utilities.DrawHeader function to reduce duplicate OnGUI code 2024-12-10 19:01:23 +03:00
yasirkula e63ebd7f85 Simplifications in Utilities.IsEmpty 2024-12-10 18:59:28 +03:00
yasirkula d5b082c093 Added "Hide Search Results" to search result groups' context menu if their search results are filtered via a search term (i.e. text filtering). For example, you can filter search results with term "[Prefab object]" and then right click the group and select this option to hide all prefab instance occurrences in that group 2024-11-03 12:52:18 +03:00
yasirkula 1faa789f48 Removed an unused variable 2024-11-02 14:56:30 +03:00
yasirkula 610fffc763 Added "Hide non-overridden prefab variables in scenes" setting (closed #42) + Renamed "Hide redundant prefab variant links" to "Hide non-overridden prefab variables in assets" 2024-11-02 14:55:40 +03:00
yasirkula 9fddcab6fa Added 'Hide unused sub-assets in "Unused Objects" list if their parent assets are used' option to Settings (closed #39) 2024-08-04 13:24:44 +03:00
yasirkula 66dd66787c Fixed NullReferenceException on newest Unity versions if VFX Graph package is installed 2024-05-12 13:02:28 +03:00
yasirkula da921c2e06 "Hide redundant prefab variant links" setting now works as expected, only affecting variables in components and not affecting prefab/MonoScript usages 2023-11-18 17:53:42 +03:00
yasirkula d9cc52cc37 Fixed some properties not being searched in edge cases that may occur when Addressables or VFX Graph packages are present in the project 2023-11-18 17:50:27 +03:00
yasirkula e6641bef48 "Show Root Asset's Name" setting is enabled by default + root asset's name is prepended by "in" word for more clarity 2023-11-18 17:46:28 +03:00
yasirkula a6d91a58a3 Scenes in read-only packages aren't searched since they can't be opened (fixed #36) (closed #37) 2023-11-18 17:45:22 +03:00
yasirkula ace8ac4947 Bumped version 2023-10-07 20:43:03 +03:00
yasirkula 02167c28a2 "Show Children In New Window" window no longer auto-closes when clicked outside 2023-10-07 20:42:53 +03:00
yasirkula 092b80ba29 Fixed some references initially being displayed collapsed after the search 2023-10-07 20:41:10 +03:00
yasirkula 524965aee7 If an exception is thrown while accessing a variable via reflection, a more detailed error message is logged 2023-10-07 20:40:21 +03:00
yasirkula efad9fa158 Muted an exception that is raised while searching "ref struct"s for reference 2023-10-07 20:39:31 +03:00
yasirkula 6cd2b407cc Scene lighting settings are now searched for references (can be turned off) 2023-10-07 20:38:37 +03:00
yasirkula 3c4292159a Fixed deprecated EditorSceneManager warnings on 2022.2+ 2023-08-31 07:10:51 +03:00
yasirkula 1a2eba24bd Added a setting to show sub-assets' root asset names in search results (disabled by default) (closes #35) 2023-06-27 14:02:34 +03:00
yasirkula cf0fea56ab Fixed 3D model assets' direct children not being pinged correctly when selected via a search result 2023-06-27 14:01:20 +03:00
yasirkula 956aea1ced Added GitHub Sponsors link to README 2023-05-31 11:21:14 +03:00
Süleyman Yasir KULA 466a152ba6 Update README.md 2023-05-07 21:49:19 +03:00
yasirkula 5eda0c1cb0 Added VFX Graph support 2023-05-07 21:47:22 +03:00
yasirkula 42e3278129 Fixed not being able to ping some asset search results in Project window (in particular, VFX graph search results) 2023-05-07 21:38:28 +03:00
yasirkula f6a999f053 Fixed an exception that occurs when a VFX Graph window is open and the open VFX Graph asset is searched for references (there may be other similar edge cases, as well) 2023-05-07 21:37:38 +03:00
yasirkula 8441e4701c Addressables support no longer requires manual modifications 2023-05-07 21:36:05 +03:00
yasirkula d57a707678 Fixed exceptions while searching for some URP assets' references due to their overriden GetHashCode functions 2023-03-18 15:12:13 +03:00
yasirkula 3fa3344507 Fixed #33 2023-03-18 15:09:37 +03:00
yasirkula 8072530c2c Added experimental Addressables support (requires manual modifications) (closed #29) 2022-10-15 17:11:42 +03:00
yasirkula 28a73e2843 Shaders are searched for #include_with_pragmas references in addition to #include references 2022-09-23 14:17:52 +03:00
yasirkula c7e52466ef Added Collapse All button to Asset Usage Detector window's context menu that collapses all search result groups at once 2022-09-23 14:16:52 +03:00
yasirkula 875f3e6794 Fixed right clicking Unused Objects group throwing an exception if that search result group hasn't been expanded yet 2022-09-23 14:16:04 +03:00
yasirkula 635d0653fa Material's color and mainTexture properties aren't searched at runtime since they're searched by SearchMaterial anyways and they can actually throw errors in the Console if the corresponding shader property doesn't exist 2022-09-23 14:15:13 +03:00
yasirkula cb4454b493 - Terrains are now searched properly
- Fixed an error on latest Unity versions when clicking the "Reset Search" button
2022-07-23 21:53:11 +03:00
yasirkula dfb8541605 Fixed compiler errors on 2021.2 and later 2022-04-24 15:14:47 +03:00
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
yasirkula 6939dbc088 - Completely changed how search results are displayed. They are now rendered as tree views which allows multi-selection, search, hiding desired rows, keyboard navigation, easy collapse/expand of multiple rows and more!
- Unused objects among the searched objects can now be found (experimental)
- It's now possible to search unused material properties, as well (e.g. normal map of a material that no longer uses normal mapping)
- Class/interface inheritance references can now be found (not always possible due to Unity's limitation in the used API)
- Most settings/colors can be tweaked from Project Settings
- Asset Usage Detector window can now be locked. When all open windows are locked, "Search for References" automatically opens a new window
- It's possible to configure whether clicked search results should immediately be selected in Hierarchy/Project or only on double click (or never at all)
- Optimizations and bugfixes
2022-01-01 21:40:37 +03:00
yasirkula dd922e85e4 Lists like "Search references of:" can now be cleared by right clicking 2021-12-19 19:05:32 +03:00
yasirkula 9648f856d1 When a scene object had a reference to a prefab and one of that prefab's children used a searched asset (e.g. a sprite), that reference couldn't be found (it's surprising how this bug couldn't be detected for so long). Fixed! 2021-12-19 19:04:34 +03:00
yasirkula f724dd2fdb References to a scene object's prefab parent's prefab parent (at any depth) are now found correctly 2021-12-19 19:02:35 +03:00
yasirkula 7b3b7957d8 Updated Known Limitations 2021-12-04 17:05:28 +03:00
yasirkula d5942a66c4 "Open X in prefab mode to select and edit Y" messages aren't spammed 2021-12-04 17:04:19 +03:00
yasirkula dcc5d5e0ad It's now possible to only highlight the clicked search results instead of actually selecting them via the window's context menu 2021-12-04 17:03:45 +03:00
yasirkula 8872a0fcc5 Exceptions encountered during search are logged using Debug.LogException so that stacktrace line numbers are clickable 2021-12-04 17:01:43 +03:00
yasirkula 8c04db9b25 Fixed multi-selection bug in search results 2021-12-04 17:00:21 +03:00
yasirkula b7b6f8815e Search results in scenes are simplified (i.e. 'Scene object A->Scene object B->Scene object C->Searched asset' references now become 'Scene object C->Searched asset') 2021-11-28 19:42:17 +03:00
yasirkula 40a28f5961 Fixed a bug where 'Scene object->Prefab->Asset' references would sometimes be skipped if Scene object wasn't referencing the correct component of the prefab 2021-11-28 19:35:37 +03:00
yasirkula b535e09ba2 Fixed a crucial bug that would cause some valid references to be skipped (e.g. Camera's 'Target Texture') 2021-11-28 19:32:16 +03:00
Süleyman Yasir KULA 499e4bc43e Added Discord link 2021-10-28 20:09:31 +03:00
yasirkula 93c955993a Previous commit applies to 'Refresh' buttons, as well 2021-10-21 15:08:46 +03:00
yasirkula 21f8daffde - Search can now be started even if some scene(s) aren't saved but the search results in those scene(s) may be incorrect
- lazySceneSearch and showDetailedProgressBar are enabled by default for better UX
2021-10-21 14:56:51 +03:00
yasirkula 8cc7798f17 Fixed a rare ArgumentNullException when searching an Animation/Animator component (#28) 2021-09-26 12:33:44 +03:00
yasirkula 45b0f6f1d9 Version 1.9.7 2021-07-25 18:00:33 +03:00
yasirkula c599ea6273 Duplicate asset usage descriptions in search results page are now omitted (i.e. "[Usage information][Usage information] Some asset" becomes "[Usage information] Some asset") 2021-07-25 17:49:30 +03:00
yasirkula 7ba33e2d4e When an asset in "Find references of:" list is right clicked, Refresh button appears which refreshes that asset's sub-assets list 2021-07-25 17:39:12 +03:00
yasirkula ac294324dd When a folder is assigned to a sprite atlas, all sprites in that folder are searched 2021-07-25 17:23:17 +03:00
yasirkula 8dc7d5508b ParticleSystem's Sub Emitters module is now searched correctly 2021-07-25 17:22:00 +03:00
Nika Burimenko c9131811e2 Sprites assigned to Particle System's Texture Sheet Animation Module are now detected (#26)
Fixed Sprite within Particle System's Texture Sheet Animation not being detected

Authored-by: Nika Burimenko <remedy89@gmail.com>
2021-07-25 16:37:44 +03:00
yasirkula 133b8b1227 Fixed small text issue on 2019.1 and 2019.2 (some devices might not have been affected by this issue) 2021-07-06 17:49:31 +03:00
yasirkula 1db9dbf9b0 Fixed issues with mysterious empty dependencies returned by AssetDatabase.GetDependencies 2021-06-09 12:35:25 +03:00
yasirkula a6b0f5ae92 Unity 2020 support 2021-05-18 13:47:38 +03:00
Süleyman Yasir KULA 8e7369e44e Some properties in Project Settings like "Quality Settings->SRP Asset" weren't included in search, fixed 2021-03-28 19:57:44 +03:00
Süleyman Yasir KULA 7b60eeacf7 If an exception occurs while searching for references via reflection, the problematic object will be skipped and a warning will be logged to the console instead of interrupting the whole search 2021-03-17 16:13:24 +03:00
Süleyman Yasir KULA b8470536b9 - Following variables of ParticleSystem are now included in search: LightsModule->Light, CollisionModule->Plane, TriggerModule->Collider
- Improved readability of texts in dark Editor skin
- Fixed "Animator is not playing an AnimatorController" warnings
- Fixed "TMP_Sprite Animator" component getting added to TextMesh Pro objects in the scene while searching for a scene object's references at runtime
2021-03-14 17:15:00 +03:00
Süleyman Yasir KULA 1bebc8691d Update package.json
Added documentationUrl, changelogUrl and licensesUrl to package.json
2021-01-19 12:51:21 +03:00
Süleyman Yasir KULA 5a81e5011b While using the Search for References button in right-click menu, if current scene setup is different from the initial scene setup, plugin now asks user whether or not they want to restore the initial scene setup instead of automatically restoring the initial scene setup 2020-12-22 22:46:22 +03:00
Süleyman Yasir KULA ba7539d983 References from Animator Override Controllers to their base Animator Controllers are now found 2020-11-18 13:46:42 +03:00
Süleyman Yasir KULA f4129574fb - Custom meshes used in ParticleSystem's Renderer module weren't included in the search, fixed
- Fix an exception that occurred when searching an Assembly Definition File's references if one of its References was missing
2020-10-01 13:43:23 +03:00
Süleyman Yasir KULA 7738da9d19 "Search for References-Include Children" didn't include inactive child objects in search, fixed 2020-09-23 23:12:47 +03:00
Süleyman Yasir KULA 077505a217 Fixed a rare issue that occurs when searching properties with ref returns for references in Play mode 2020-08-20 12:24:37 +03:00
Süleyman Yasir KULA 003cedd363 - Added 2 options to the "Search for References" button in Hierarchy objects' context (right-click) menu: "This Object Only" and "Include Children"
- In search results, "arrayVariable.Array.data[0]" is now displayed as "arrayVariable[0]"
2020-08-08 19:52:59 +03:00
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
Süleyman Yasir KULA 12ed06d43c - Added Refresh button to groups (scene/project window) in search results page to refresh the search results for that particular group
- Added collapse/expand button to groups in search results page
- Added lazy scene search option: when enabled, unloaded scenes that have potential references are not loaded immediately; instead, they are searched on demand (via Refresh button)(faster search)
- Search algorithm now prefers SerializedObjects when possible, uses reflection as fallback
- Added "Search for References" to Hierarchy objects' right-click context menu
- Searching for references of objects in prefab mode is now supported
- A simple search progress bar is now always shown, but is not refreshed frequently unless "Show detailed progress bar" is enabled and thus, it won't affect the search performance noticably
- Removed settings like "Search properties" and "Search depth", it doesn't make much sense to limit the search algorithm in an asset whose sole purpose is to find "all" references
- Removed "Select All (GameObject-wise)" and "Select All (Component-wise)" buttons (use CTRL or Shift keys to enable multi-select while clicking search entries in results page)
- Double clicking a prefab entry in search results page will now open that prefab in prefab mode
2019-11-09 17:22:35 +03:00
Süleyman Yasir KULA 69ce197932 Catching MissingComponentException 2019-10-18 23:53:25 +03:00
37 changed files with 7178 additions and 1909 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+73
View File
@@ -0,0 +1,73 @@
# Asset Usage Detector for Unity 3D
![Settings](Images/Settings.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/
**Discord:** https://discord.gg/UJJt549AaV
**[GitHub Sponsors ☕](https://github.com/sponsors/yasirkula)**
## 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. 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)* click the + button and install the package from the following git URL:
- `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**
- 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
- *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
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,29 @@
{
"name": "AssetUsageDetector.Editor",
"rootNamespace": "",
"references": [
"Unity.Addressables"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"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
}
@@ -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,207 @@
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];
int length = dependencies.Length;
for( int i = 0; i < length; i++ )
{
if( !string.IsNullOrEmpty( dependencies[i] ) )
{
FileInfo assetFile = new FileInfo( dependencies[i] );
fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L;
}
else
{
// This dependency is empty which causes issues when passed to FileInfo constructor
// Find a non-empty dependency and move it to this index
for( int j = length - 1; j > i; j--, length-- )
{
if( !string.IsNullOrEmpty( dependencies[j] ) )
{
dependencies[i--] = dependencies[j];
break;
}
}
length--;
}
}
if( length != fileSizes.Length )
{
Array.Resize( ref dependencies, length );
Array.Resize( ref fileSizes, length );
}
}
}
#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:
@@ -0,0 +1,289 @@
using UnityEditor;
using UnityEngine;
namespace AssetUsageDetectorNamespace
{
public static class AssetUsageDetectorSettings
{
private static readonly GUILayoutOption GL_WIDTH_60 = GUILayout.Width( 60f );
#region Colors
private static Color? m_settingsHeaderColor = null;
public static Color SettingsHeaderColor
{
get { if( m_settingsHeaderColor == null ) m_settingsHeaderColor = GetColor( "AUD_SettingsHeaderTint", Color.cyan ); return m_settingsHeaderColor.Value; }
set { if( m_settingsHeaderColor == value ) return; m_settingsHeaderColor = value; SetColor( "AUD_SettingsHeaderTint", value ); }
}
private static Color? m_searchResultGroupHeaderColor = null;
public static Color SearchResultGroupHeaderColor
{
get { if( m_searchResultGroupHeaderColor == null ) m_searchResultGroupHeaderColor = GetColor( "AUD_ResultGroupHeaderTint", Color.cyan ); return m_searchResultGroupHeaderColor.Value; }
set { if( m_searchResultGroupHeaderColor == value ) return; m_searchResultGroupHeaderColor = value; SetColor( "AUD_ResultGroupHeaderTint", value ); }
}
private static Color? m_rootRowsBackgroundColor = null;
public static Color RootRowsBackgroundColor
{
get { if( m_rootRowsBackgroundColor == null ) m_rootRowsBackgroundColor = GetColor( "AUD_RootRowsTint", EditorGUIUtility.isProSkin ? new Color( 0f, 1f, 1f, 0.15f ) : new Color( 0f, 1f, 1f, 0.25f ) ); return m_rootRowsBackgroundColor.Value; }
set { if( m_rootRowsBackgroundColor == value ) return; m_rootRowsBackgroundColor = value; SetColor( "AUD_RootRowsTint", value ); }
}
private static Color? m_rootRowsBorderColor = null;
public static Color RootRowsBorderColor
{
get { if( m_rootRowsBorderColor == null ) m_rootRowsBorderColor = GetColor( "AUD_RootRowsBorderColor", EditorGUIUtility.isProSkin ? new Color( 0.15f, 0.15f, 0.15f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); return m_rootRowsBorderColor.Value; }
set { if( m_rootRowsBorderColor == value ) return; m_rootRowsBorderColor = value; SetColor( "AUD_RootRowsBorderColor", value ); }
}
private static Color? m_mainReferencesBackgroundColor = null;
public static Color MainReferencesBackgroundColor
{
get { if( m_mainReferencesBackgroundColor == null ) m_mainReferencesBackgroundColor = GetColor( "AUD_MainRefRowsTint", EditorGUIUtility.isProSkin ? new Color( 0f, 0.35f, 0f, 1f ) : new Color( 0.25f, 0.75f, 0.25f, 1f ) ); return m_mainReferencesBackgroundColor.Value; }
set { if( m_mainReferencesBackgroundColor == value ) return; m_mainReferencesBackgroundColor = value; SetColor( "AUD_MainRefRowsTint", value ); }
}
private static Color? m_selectedRowsParentTint = null;
public static Color SelectedRowParentsTint
{
get { if( m_selectedRowsParentTint == null ) m_selectedRowsParentTint = GetColor( "AUD_SelectedRowParentsTint", EditorGUIUtility.isProSkin ? new Color( 0.36f, 0.36f, 0.18f, 1f ) : new Color( 0.825f, 0.825f, 0.55f, 1f ) ); return m_selectedRowsParentTint.Value; }
set { if( m_selectedRowsParentTint == value ) return; m_selectedRowsParentTint = value; SetColor( "AUD_SelectedRowParentsTint", value ); }
}
private static Color? m_selectedRowOccurrencesColor = null;
public static Color SelectedRowOccurrencesColor
{
get { if( m_selectedRowOccurrencesColor == null ) m_selectedRowOccurrencesColor = GetColor( "AUD_SelectedRowOccurrencesTint", EditorGUIUtility.isProSkin ? new Color( 0f, 0.3f, 0.75f, 1f ) : new Color( 0.25f, 0.75f, 1f, 1f ) ); return m_selectedRowOccurrencesColor.Value; }
set { if( m_selectedRowOccurrencesColor == value ) return; m_selectedRowOccurrencesColor = value; SetColor( "AUD_SelectedRowOccurrencesTint", value ); }
}
private static Color? m_treeLinesColor = null;
public static Color TreeLinesColor
{
get { if( m_treeLinesColor == null ) m_treeLinesColor = GetColor( "AUD_TreeLinesColor", EditorGUIUtility.isProSkin ? new Color( 0.65f, 0.65f, 0.65f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); return m_treeLinesColor.Value; }
set { if( m_treeLinesColor == value ) return; m_treeLinesColor = value; SetColor( "AUD_TreeLinesColor", value ); }
}
private static Color? m_highlightedTreeLinesColor = null;
public static Color HighlightedTreeLinesColor
{
get { if( m_highlightedTreeLinesColor == null ) m_highlightedTreeLinesColor = GetColor( "AUD_HighlightTreeLinesColor", Color.cyan ); return m_highlightedTreeLinesColor.Value; }
set { if( m_highlightedTreeLinesColor == value ) return; m_highlightedTreeLinesColor = value; SetColor( "AUD_HighlightTreeLinesColor", value ); }
}
private static Color? m_searchMatchingTextColor = null;
public static Color SearchMatchingTextColor
{
get { if( m_searchMatchingTextColor == null ) m_searchMatchingTextColor = GetColor( "AUD_SearchTextColor", Color.red ); return m_searchMatchingTextColor.Value; }
set { if( m_searchMatchingTextColor == value ) return; m_searchMatchingTextColor = value; SetColor( "AUD_SearchTextColor", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged( highlightedSearchTextColorChanged: true ) ); }
}
private static Color? m_tooltipDescriptionTextColor = null;
public static Color TooltipDescriptionTextColor
{
get { if( m_tooltipDescriptionTextColor == null ) m_tooltipDescriptionTextColor = GetColor( "AUD_TooltipUsageTextColor", EditorGUIUtility.isProSkin ? new Color( 0f, 0.9f, 0.9f, 1f ) : new Color( 0.9f, 0f, 0f, 1f ) ); return m_tooltipDescriptionTextColor.Value; }
set { if( m_tooltipDescriptionTextColor == value ) return; m_tooltipDescriptionTextColor = value; SetColor( "AUD_TooltipUsageTextColor", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged( tooltipDescriptionsColorChanged: true ) ); }
}
#endregion
#region Size Adjustments
private static float? m_extraRowHeight = null;
public static float ExtraRowHeight
{
get { if( m_extraRowHeight == null ) m_extraRowHeight = EditorPrefs.GetFloat( "AUD_ExtraRowHeight", 0f ); return m_extraRowHeight.Value; }
set { if( m_extraRowHeight == value ) return; m_extraRowHeight = value; EditorPrefs.SetFloat( "AUD_ExtraRowHeight", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged() ); }
}
#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
{
get { if( m_pingClickedObjects == null ) m_pingClickedObjects = EditorPrefs.GetBool( "AUD_PingClickedObj", true ); return m_pingClickedObjects.Value; }
set { if( m_pingClickedObjects == value ) return; m_pingClickedObjects = value; EditorPrefs.SetBool( "AUD_PingClickedObj", value ); }
}
private static bool? m_selectClickedObjects = null;
public static bool SelectClickedObjects
{
get { if( m_selectClickedObjects == null ) m_selectClickedObjects = EditorPrefs.GetBool( "AUD_SelectClickedObj", false ); return m_selectClickedObjects.Value; }
set { if( m_selectClickedObjects == value ) return; m_selectClickedObjects = value; EditorPrefs.SetBool( "AUD_SelectClickedObj", value ); }
}
private static bool? m_selectDoubleClickedObjects = null;
public static bool SelectDoubleClickedObjects
{
get { if( m_selectDoubleClickedObjects == null ) m_selectDoubleClickedObjects = EditorPrefs.GetBool( "AUD_SelectDoubleClickedObj", true ); return m_selectDoubleClickedObjects.Value; }
set { if( m_selectDoubleClickedObjects == value ) return; m_selectDoubleClickedObjects = value; EditorPrefs.SetBool( "AUD_SelectDoubleClickedObj", value ); }
}
private static bool? m_markUsedAssetsSubAssetsAsUsed = null;
public static bool MarkUsedAssetsSubAssetsAsUsed
{
get { if( m_markUsedAssetsSubAssetsAsUsed == null ) m_markUsedAssetsSubAssetsAsUsed = EditorPrefs.GetBool( "AUD_MarkUsedAssetsSubAssetsAsUsed", true ); return m_markUsedAssetsSubAssetsAsUsed.Value; }
set { if( m_markUsedAssetsSubAssetsAsUsed == value ) return; m_markUsedAssetsSubAssetsAsUsed = value; EditorPrefs.SetBool( "AUD_MarkUsedAssetsSubAssetsAsUsed", value ); }
}
private static bool? m_showUnityTooltip = null;
public static bool ShowUnityTooltip
{
get { if( m_showUnityTooltip == null ) m_showUnityTooltip = EditorPrefs.GetBool( "AUD_ShowUnityTooltip", false ); return m_showUnityTooltip.Value; }
set { if( m_showUnityTooltip == value ) return; m_showUnityTooltip = value; EditorPrefs.SetBool( "AUD_ShowUnityTooltip", value ); }
}
private static bool? m_showCustomTooltip = null;
public static bool ShowCustomTooltip
{
get { if( m_showCustomTooltip == null ) m_showCustomTooltip = EditorPrefs.GetBool( "AUD_ShowCustomTooltip", true ); return m_showCustomTooltip.Value; }
set { if( m_showCustomTooltip == value ) return; m_showCustomTooltip = value; EditorPrefs.SetBool( "AUD_ShowCustomTooltip", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged() ); }
}
private static float? m_customTooltipDelay = null;
public static float CustomTooltipDelay
{
get { if( m_customTooltipDelay == null ) m_customTooltipDelay = EditorPrefs.GetFloat( "AUD_CustomTooltipDelay", 0.7f ); return m_customTooltipDelay.Value; }
set { if( m_customTooltipDelay == value ) return; m_customTooltipDelay = value; EditorPrefs.SetFloat( "AUD_CustomTooltipDelay", value ); }
}
private static bool? m_showTreeLines = null;
public static bool ShowTreeLines
{
get { if( m_showTreeLines == null ) m_showTreeLines = EditorPrefs.GetBool( "AUD_ShowTreeLines", true ); return m_showTreeLines.Value; }
set { if( m_showTreeLines == value ) return; m_showTreeLines = value; EditorPrefs.SetBool( "AUD_ShowTreeLines", value ); }
}
private static bool? m_applySelectedRowParentsTintToRootRows = null;
public static bool ApplySelectedRowParentsTintToRootRows
{
get { if( m_applySelectedRowParentsTintToRootRows == null ) m_applySelectedRowParentsTintToRootRows = EditorPrefs.GetBool( "AUD_SelectedRowParentsTintAtRoot", true ); return m_applySelectedRowParentsTintToRootRows.Value; }
set { if( m_applySelectedRowParentsTintToRootRows == value ) return; m_applySelectedRowParentsTintToRootRows = value; EditorPrefs.SetBool( "AUD_SelectedRowParentsTintAtRoot", value ); }
}
#endregion
[SettingsProvider]
public static SettingsProvider CreatePreferencesGUI()
{
return new SettingsProvider( "Project/yasirkula/Asset Usage Detector", SettingsScope.Project )
{
guiHandler = ( searchContext ) => PreferencesGUI(),
keywords = new System.Collections.Generic.HashSet<string>() { "Asset", "Usage", "Detector" }
};
}
public static void PreferencesGUI()
{
float labelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth += 60f;
EditorGUI.BeginChangeCheck();
ShowRootAssetName = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Root Asset's Name For Sub-Assets (Requires Refresh)", ShowRootAssetName );
EditorGUILayout.Space();
PingClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Ping Clicked Objects", PingClickedObjects );
SelectClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Select Clicked Objects", SelectClickedObjects );
SelectDoubleClickedObjects = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Select Double Clicked Objects", SelectDoubleClickedObjects );
EditorGUILayout.Space();
MarkUsedAssetsSubAssetsAsUsed = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Hide unused sub-assets in \"Unused Objects\" list if their parent assets are used (Requires Refresh)", MarkUsedAssetsSubAssetsAsUsed );
EditorGUILayout.Space();
ShowUnityTooltip = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Unity Tooltip", ShowUnityTooltip );
ShowCustomTooltip = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Custom Tooltip", ShowCustomTooltip );
EditorGUI.indentLevel++;
CustomTooltipDelay = FloatField( "Delay", CustomTooltipDelay, 0.7f );
EditorGUI.indentLevel--;
TooltipDescriptionTextColor = ColorField( "Tooltip Descriptions Text Color", TooltipDescriptionTextColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.9f, 0.9f, 1f ) : new Color( 0.9f, 0f, 0f, 1f ) );
EditorGUILayout.Space();
ExtraRowHeight = Mathf.Max( 0f, FloatField( "Extra Row Height", ExtraRowHeight, 0f ) );
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 ) );
MainReferencesBackgroundColor = ColorField( "Main References Background Color", MainReferencesBackgroundColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.35f, 0f, 1f ) : new Color( 0.25f, 0.75f, 0.25f, 1f ) );
SelectedRowParentsTint = ColorField( "Selected Row Parents Tint", SelectedRowParentsTint, EditorGUIUtility.isProSkin ? new Color( 0.36f, 0.36f, 0.18f, 1f ) : new Color( 0.825f, 0.825f, 0.55f, 1f ) );
EditorGUI.indentLevel++;
ApplySelectedRowParentsTintToRootRows = !EditorGUILayout.Toggle( "Ignore Root Rows", !ApplySelectedRowParentsTintToRootRows );
EditorGUI.indentLevel--;
SelectedRowOccurrencesColor = ColorField( "Selected Row All Occurrences Tint", SelectedRowOccurrencesColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.3f, 0.75f, 1f ) : new Color( 0.25f, 0.75f, 1f, 1f ) );
SearchMatchingTextColor = ColorField( "Matching Search Text Color", SearchMatchingTextColor, Color.red );
ShowTreeLines = AssetUsageDetectorWindow.WordWrappingToggleLeft( "Show Tree Lines", ShowTreeLines );
EditorGUI.indentLevel++;
TreeLinesColor = ColorField( "Normal Color", TreeLinesColor, EditorGUIUtility.isProSkin ? new Color( 0.65f, 0.65f, 0.65f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) );
HighlightedTreeLinesColor = ColorField( "Highlighted Color", HighlightedTreeLinesColor, Color.cyan );
EditorGUI.indentLevel--;
EditorGUIUtility.labelWidth = labelWidth;
if( EditorGUI.EndChangeCheck() )
ForEachAssetUsageDetectorWindow( ( window ) => window.Repaint() );
}
private static Color ColorField( string label, Color value, Color defaultValue )
{
GUILayout.BeginHorizontal();
Color result = EditorGUILayout.ColorField( label, value );
if( GUILayout.Button( "Reset", GL_WIDTH_60 ) )
result = defaultValue;
GUILayout.EndHorizontal();
return result;
}
private static float FloatField( string label, float value, float defaultValue )
{
GUILayout.BeginHorizontal();
float result = EditorGUILayout.FloatField( label, value );
if( GUILayout.Button( "Reset", GL_WIDTH_60 ) )
result = defaultValue;
GUILayout.EndHorizontal();
return result;
}
private static Color GetColor( string pref, Color defaultColor )
{
if( EditorGUIUtility.isProSkin )
pref += "_Pro";
if( !EditorPrefs.HasKey( pref ) )
return defaultColor;
string[] parts = EditorPrefs.GetString( pref ).Split( ';' );
return new Color32( byte.Parse( parts[0] ), byte.Parse( parts[1] ), byte.Parse( parts[2] ), byte.Parse( parts[3] ) );
}
private static void SetColor( string pref, Color32 value )
{
if( EditorGUIUtility.isProSkin )
pref += "_Pro";
EditorPrefs.SetString( pref, string.Concat( value.r.ToString(), ";", value.g.ToString(), ";", value.b.ToString(), ";", value.a.ToString() ) );
}
private static void ForEachAssetUsageDetectorWindow( System.Action<AssetUsageDetectorWindow> action )
{
foreach( AssetUsageDetectorWindow window in Resources.FindObjectsOfTypeAll<AssetUsageDetectorWindow>() )
{
if( window )
action( window );
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 13295073724765e45aa3b77486e515f4
timeCreated: 1639982865
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public class EmptyEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
@@ -112,5 +112,19 @@ namespace AssetUsageDetectorNamespace.Extras
{
return GetEnumerator();
}
public Object[] ToArray()
{
int count = 0;
foreach( Object obj in this )
count++;
Object[] result = new Object[count];
int index = 0;
foreach( Object obj in this )
result[index++] = obj;
return result;
}
}
}
@@ -2,7 +2,7 @@
using UnityEditor;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public abstract class ListDrawer<T>
{
@@ -31,8 +31,7 @@ namespace AssetUsageDetectorNamespace.Extras
{
// Handle drag & drop references to array
// Credit: https://answers.unity.com/answers/657877/view.html
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) &&
GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if( ev.type == EventType.DragPerform )
@@ -46,8 +45,22 @@ namespace AssetUsageDetectorNamespace.Extras
{
if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) )
{
bool replacedNullElement = false;
for( int j = 0; j < list.Count; j++ )
{
if( IsElementNull( list[j] ) )
{
list[j] = CreateElement( draggedObjects[i] );
replacedNullElement = true;
break;
}
}
if( !replacedNullElement )
list.Add( CreateElement( draggedObjects[i] ) );
hasChanged = true;
list.Add( CreateElement( draggedObjects[i] ) );
}
}
}
@@ -55,6 +68,18 @@ namespace AssetUsageDetectorNamespace.Extras
ev.Use();
}
else if( ev.type == EventType.ContextClick && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
GenericMenu contextMenu = new GenericMenu();
contextMenu.AddItem( new GUIContent( "Clear" ), false, () =>
{
list.Clear();
list.Add( CreateElement( null ) );
} );
contextMenu.ShowAsContext();
ev.Use();
}
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
list.Insert( 0, CreateElement( null ) );
@@ -72,7 +97,7 @@ namespace AssetUsageDetectorNamespace.Extras
Object prevObject = GetObjectFromElement( element );
Object newObject = EditorGUILayout.ObjectField( "", prevObject, typeof( Object ), acceptSceneObjects );
if( GUI.changed && prevObject != newObject )
if( GUI.changed )
{
hasChanged = true;
SetObjectOfElement( list, i, newObject );
@@ -107,6 +132,7 @@ namespace AssetUsageDetectorNamespace.Extras
protected abstract T CreateElement( Object source );
protected abstract Object GetObjectFromElement( T element );
protected abstract void SetObjectOfElement( List<T> list, int index, Object value );
protected abstract bool IsElementNull( T element );
protected abstract void PostElementDrawer( T element );
}
@@ -131,6 +157,11 @@ namespace AssetUsageDetectorNamespace.Extras
list[index] = value;
}
protected override bool IsElementNull( Object element )
{
return element == null || element.Equals( null );
}
protected override void PostElementDrawer( Object element )
{
}
@@ -158,6 +189,11 @@ namespace AssetUsageDetectorNamespace.Extras
list[index].RefreshSubAssets();
}
protected override bool IsElementNull( ObjectToSearch element )
{
return element == null || element.obj == null || element.obj.Equals( null );
}
protected override void PostElementDrawer( ObjectToSearch element )
{
List<ObjectToSearch.SubAsset> subAssetsToSearch = element.subAssets;
@@ -2,9 +2,10 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.U2D;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
[Serializable]
public class ObjectToSearch
@@ -26,16 +27,15 @@ namespace AssetUsageDetectorNamespace.Extras
public List<SubAsset> subAssets;
public bool showSubAssetsFoldout;
private static MonoScript[] monoScriptsInProject;
private static HashSet<Object> currentSubAssets;
public ObjectToSearch( Object obj )
public ObjectToSearch( Object obj, bool? shouldSearchChildren = null )
{
this.obj = obj;
RefreshSubAssets();
RefreshSubAssets( shouldSearchChildren );
}
public void RefreshSubAssets()
public void RefreshSubAssets( bool? shouldSearchChildren = null )
{
if( subAssets == null )
subAssets = new List<SubAsset>();
@@ -47,87 +47,87 @@ namespace AssetUsageDetectorNamespace.Extras
else
currentSubAssets.Clear();
AddSubAssets( obj, false );
AddSubAssets( obj, false, shouldSearchChildren );
currentSubAssets.Clear();
}
private void AddSubAssets( Object target, bool includeTarget )
private void AddSubAssets( Object target, bool includeTarget, bool? shouldSearchChildren )
{
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>( true );
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, shouldSearchChildren ?? 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.Add( target ) )
subAssets.Add( new SubAsset( target, shouldSearchChildren ?? true ) );
}
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
else
{
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
continue;
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
// If asset is a directory, add all of its contents as sub-assets recursively
if( target.IsFolder() )
{
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] ) );
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true, shouldSearchChildren );
return;
}
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
// Add Sprites of SpriteAtlases to the sub-assets list
if( target is SpriteAtlas spriteAtlas )
{
Sprite[] packedSprites = AssetUsageDetector.spriteAtlasPackedSpritesGetter( spriteAtlas );
if( packedSprites != null )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
for( int i = 0; i < packedSprites.Length; i++ )
{
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
if( packedSprites[i] != null && currentSubAssets.Add( packedSprites[i] ) )
subAssets.Add( new SubAsset( packedSprites[i], shouldSearchChildren ?? true ) );
}
}
}
// Find sub-asset(s) of the asset (if any)
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 || asset == target )
continue;
// Nested prefabs in prefab assets add an additional native object of type 'UnityEngine.PrefabInstance' to the prefab. Managed type of that native type
// is UnityEngine.Object (i.e. GetType() returns UnityEngine.Object, not UnityEngine.PrefabInstance). There are no possible references to these native
// objects so skip them (we're checking for UnityEngine.Prefab because it includes other native types like UnityEngine.PrefabCreation, as well)
if( target is GameObject && asset.GetType() == typeof( Object ) && asset.ToString().Contains( "(UnityEngine.Prefab" ) )
continue;
if( currentSubAssets.Add( asset ) )
subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) );
}
}
}
}
}
}
@@ -0,0 +1,374 @@
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;
case SerializedPropertyType.ManagedReference: SerializedProperty.managedReferenceValue = newValue; break;
}
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 );
List<string> nonModifiableTextureNames = new List<string>( 16 );
List<Texture> nonModifiableTextureValues = new List<Texture>( 16 );
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( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) )
{
Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable )
propertyDefaultValue = (Texture) newValue;
nonModifiableTextureNames.Add( propertyName );
nonModifiableTextureValues.Add( propertyDefaultValue );
}
else
{
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() );
shaderImporter.SetNonModifiableTextures( nonModifiableTextureNames.ToArray(), nonModifiableTextureValues.ToArray() );
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:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,91 @@
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace AssetUsageDetectorNamespace
{
public class SearchResultTooltip : EditorWindow
{
private static SearchResultTooltip mainWindow;
private static string tooltip;
private static GUIStyle m_style;
internal static GUIStyle Style
{
get
{
if( m_style == null )
{
m_style = (GUIStyle) typeof( EditorStyles ).GetProperty( "tooltip", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).GetValue( null, null );
m_style.richText = true;
}
return m_style;
}
}
public static void Show( Rect sourcePosition, string tooltip )
{
// Don't lose focus to the previous window
EditorWindow prevFocusedWindow = focusedWindow;
if (!mainWindow)
{
mainWindow = CreateInstance<SearchResultTooltip>();
mainWindow.ShowPopup();
}
Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical );
Rect preferredPosition;
Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize );
Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect(positionLeft, mainWindow);
Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position;
Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size;
if( positionOffset.sqrMagnitude <= 400f && sizeOffset.sqrMagnitude <= 400f )
preferredPosition = screenFittedPositionLeft;
else
{
Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize );
Rect screenFittedPositionRight = Utilities.GetScreenFittedRect(positionRight, mainWindow);
Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position;
Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size;
if( positionOffset2.magnitude + sizeOffset2.magnitude < positionOffset.magnitude + sizeOffset.magnitude )
preferredPosition = screenFittedPositionRight;
else
preferredPosition = screenFittedPositionLeft;
}
SearchResultTooltip.tooltip = tooltip;
mainWindow.minSize = preferredPosition.size;
mainWindow.position = preferredPosition;
mainWindow.Repaint();
if( prevFocusedWindow )
prevFocusedWindow.Focus();
}
public static void Hide()
{
if( mainWindow )
{
mainWindow.Close();
mainWindow = null;
}
}
private void OnGUI()
{
// If somehow the tooltip isn't automatically closed, allow closing it by clicking on it
if( Event.current.type == EventType.MouseDown )
{
Hide();
GUIUtility.ExitGUI();
}
GUI.Label( new Rect( Vector2.zero, position.size ), tooltip, Style );
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c8bd4351b5024324ca5974ebcad1dde3
timeCreated: 1639247551
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b3903f1d3149e9b4990e49206f8255c8
timeCreated: 1638690728
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+368 -202
View File
@@ -1,42 +1,65 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Unity.Collections;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
namespace AssetUsageDetectorNamespace.Extras
namespace AssetUsageDetectorNamespace
{
public static class Utilities
{
// A set of commonly used Unity types
private static readonly HashSet<Type> primitiveUnityTypes = new HashSet<Type>() {
typeof( string ), typeof( Vector4 ), typeof( Vector3 ), typeof( Vector2 ), typeof( Rect ),
typeof( Quaternion ), typeof( Color ), typeof( Color32 ), typeof( LayerMask ),
typeof( Matrix4x4 ), typeof( AnimationCurve ), typeof( Gradient ), typeof( RectOffset ),
typeof( bool[] ), typeof( byte[] ), typeof( sbyte[] ), typeof( char[] ), typeof( decimal[] ),
typeof( double[] ), typeof( float[] ), typeof( int[] ), typeof( uint[] ), typeof( long[] ),
typeof( ulong[] ), typeof( short[] ), typeof( ushort[] ), typeof( string[] ),
typeof( Vector4[] ), typeof( Vector3[] ), typeof( Vector2[] ), typeof( Rect[] ),
typeof( Quaternion[] ), typeof( Color[] ), typeof( Color32[] ), typeof( LayerMask[] ),
typeof( Matrix4x4[] ), typeof( AnimationCurve[] ), typeof( Gradient[] ), typeof( RectOffset[] ),
typeof( List<bool> ), typeof( List<byte> ), typeof( List<sbyte> ), typeof( List<char> ), typeof( List<decimal> ),
typeof( List<double> ), typeof( List<float> ), typeof( List<int> ), typeof( List<uint> ), typeof( List<long> ),
typeof( List<ulong> ), typeof( List<short> ), typeof( List<ushort> ), typeof( List<string> ),
typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ),
typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ),
typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> )
private static readonly HashSet<Type> primitiveUnityTypes = new HashSet<Type>()
{
typeof( string ), typeof( Vector4 ), typeof( Vector3 ), typeof( Vector2 ), typeof( Rect ),
typeof( Quaternion ), typeof( Color ), typeof( Color32 ), typeof( LayerMask ), typeof( Bounds ),
typeof( Matrix4x4 ), typeof( AnimationCurve ), typeof( Gradient ), typeof( RectOffset ),
typeof( bool[] ), typeof( byte[] ), typeof( sbyte[] ), typeof( char[] ), typeof( decimal[] ),
typeof( double[] ), typeof( float[] ), typeof( int[] ), typeof( uint[] ), typeof( long[] ),
typeof( ulong[] ), typeof( short[] ), typeof( ushort[] ), typeof( string[] ),
typeof( Vector4[] ), typeof( Vector3[] ), typeof( Vector2[] ), typeof( Rect[] ),
typeof( Quaternion[] ), typeof( Color[] ), typeof( Color32[] ), typeof( LayerMask[] ), typeof( Bounds[] ),
typeof( Matrix4x4[] ), typeof( AnimationCurve[] ), typeof( Gradient[] ), typeof( RectOffset[] ),
typeof( List<bool> ), typeof( List<byte> ), typeof( List<sbyte> ), typeof( List<char> ), typeof( List<decimal> ),
typeof( List<double> ), typeof( List<float> ), typeof( List<int> ), typeof( List<uint> ), typeof( List<long> ),
typeof( List<ulong> ), typeof( List<short> ), typeof( List<ushort> ), typeof( List<string> ),
typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ),
typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ), typeof( List<Bounds> ),
typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> ),
typeof( Vector3Int ), typeof( Vector2Int ), typeof( RectInt ), typeof( BoundsInt ),
typeof( Vector3Int[] ), typeof( Vector2Int[] ), typeof( RectInt[] ), typeof( BoundsInt[] ),
typeof( List<Vector3Int> ), typeof( List<Vector2Int> ), typeof( List<RectInt> ), typeof( List<BoundsInt> )
};
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
private static MethodInfo screenFittedRectGetter;
private static FieldInfo editorWindowHostViewGetter;
private static PropertyInfo hostViewContainerWindowGetter;
private static readonly Func<Object, bool, bool> prefabHasAnyOverridesGetter = (Func<Object, bool, bool>) Delegate.CreateDelegate( typeof( Func<Object, bool, bool> ), typeof( PrefabUtility ).GetMethod( "HasObjectOverride", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
internal static readonly StringBuilder stringBuilder = new StringBuilder( 400 );
public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true );
public static readonly GUILayoutOption GL_EXPAND_HEIGHT = GUILayout.ExpandHeight( true );
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 );
@@ -51,71 +74,110 @@ namespace AssetUsageDetectorNamespace.Extras
m_boxGUIStyle = new GUIStyle( EditorStyles.helpBox )
{
alignment = TextAnchor.MiddleCenter,
font = EditorStyles.label.font
font = EditorStyles.label.font,
richText = true
};
Color textColor = GUI.skin.button.normal.textColor;
m_boxGUIStyle.normal.textColor = textColor;
m_boxGUIStyle.hover.textColor = textColor;
m_boxGUIStyle.focused.textColor = textColor;
m_boxGUIStyle.active.textColor = textColor;
m_boxGUIStyle.fontSize = ( m_boxGUIStyle.fontSize + GUI.skin.button.fontSize ) / 2;
}
return m_boxGUIStyle;
}
}
private static GUIStyle m_tooltipGUIStyle; // GUIStyle used to draw the tooltip
public static GUIStyle TooltipGUIStyle
{
get
{
GUIStyleState normalState;
if( m_tooltipGUIStyle != null )
normalState = m_tooltipGUIStyle.normal;
else
{
m_tooltipGUIStyle = new GUIStyle( EditorStyles.helpBox )
{
alignment = TextAnchor.MiddleCenter,
font = EditorStyles.label.font
};
normalState = m_tooltipGUIStyle.normal;
normalState.background = null;
normalState.textColor = Color.black;
}
if( normalState.background == null || normalState.background.Equals( null ) )
{
Texture2D backgroundTexture = new Texture2D( 1, 1 );
backgroundTexture.SetPixel( 0, 0, new Color( 0.88f, 0.88f, 0.88f, 0.85f ) );
backgroundTexture.Apply();
normalState.background = backgroundTexture;
}
return m_tooltipGUIStyle;
}
}
// Get a unique-ish string hash code for an object
public static string Hash( this object obj )
{
if( obj is Object )
return obj.GetHashCode().ToString();
return obj.GetHashCode() + obj.GetType().Name;
}
// Check if object is an asset or a Scene object
public static bool IsAsset( this object obj )
{
return obj is Object && AssetDatabase.Contains( (Object) obj );
}
public static bool IsAsset( this Object obj )
{
return AssetDatabase.Contains( obj );
}
// Check if object is a folder asset
public static bool IsFolder( this Object obj )
{
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
}
public static T GetPrefabParent<T>( this T obj ) where T : Object
{
return PrefabUtility.GetCorrespondingObjectFromSource( obj );
}
public static bool HasAnyPrefabOverrides( this Object obj )
{
if( obj.GetPrefabParent() == null )
return false;
return prefabHasAnyOverridesGetter( obj, false );
}
public static bool HasAnyPrefabOverrides( this GameObject gameObject )
{
if( gameObject.GetPrefabParent() == null )
return false;
if( !PrefabUtility.HasPrefabInstanceAnyOverrides( gameObject, false ) )
return false;
Transform rootTransform = gameObject.transform;
List<Component> components = new List<Component>( 8 );
Stack<Transform> stack = new Stack<Transform>( 8 );
stack.Push( rootTransform );
while( stack.Count > 0 )
{
Transform transform = stack.Pop();
Transform prefab = transform.GetPrefabParent();
if( prefab == null ) // GameObject is added as override
return true;
if( transform.childCount != prefab.childCount ) // Has some added/destroyed children as override
return true;
bool isRootTransform = ReferenceEquals( transform, rootTransform );
if( !isRootTransform && ( transform.gameObject as Object ).HasAnyPrefabOverrides() ) // GameObject's properties are modified (e.g. name or tag) (excluding root GameObject)
return true;
components.Clear();
transform.GetComponents( components );
foreach( Component component in components )
{
if( component == null )
continue;
if( component.GetPrefabParent() == null ) // Component is added as override
return true;
if( ( !isRootTransform || !( component is Transform ) ) && component.HasAnyPrefabOverrides() ) // Component is modified (excluding root Transform)
return true;
}
int componentCount = components.Count;
components.Clear();
prefab.GetComponents( components );
if( components.Count != componentCount ) // Has some destroyed components as override
return true;
for( int i = 0, childCount = transform.childCount; i < childCount; i++ )
{
Transform child = transform.GetChild( i );
if( child != null )
stack.Push( child );
}
}
return false;
}
// Returns an enumerator to iterate through all asset paths in the folder
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
{
@@ -134,131 +196,149 @@ namespace AssetUsageDetectorNamespace.Extras
return folderContentsSet;
}
// Select an object in the editor
public static void SelectInEditor( this Object obj )
public static void GetObjectsToSelectAndPing( this Object obj, out Object selection, out Object pingTarget )
{
if( obj == null )
return;
Event e = Event.current;
// If CTRL key is pressed, do a multi-select;
// otherwise select only the clicked object and ping it in editor
if( !e.control )
Selection.activeObject = obj.PingInEditor();
else
if( obj == null || obj.Equals( null ) )
{
Component objAsComp = obj as Component;
GameObject objAsGO = obj as GameObject;
int selectionIndex = -1;
Object[] selection = Selection.objects;
for( int i = 0; i < selection.Length; i++ )
{
Object selected = selection[i];
// Don't allow including both a gameobject and one of its components in the selection
if( selected == obj || ( objAsComp != null && selected == objAsComp.gameObject ) ||
( objAsGO != null && selected is Component && ( (Component) selected ).gameObject == objAsGO ) )
{
selectionIndex = i;
break;
}
}
Object[] newSelection;
if( selectionIndex == -1 )
{
// Include object in selection
newSelection = new Object[selection.Length + 1];
selection.CopyTo( newSelection, 0 );
newSelection[selection.Length] = obj;
}
else
{
// Remove object from selection
newSelection = new Object[selection.Length - 1];
int j = 0;
for( int i = 0; i < selectionIndex; i++, j++ )
newSelection[j] = selection[i];
for( int i = selectionIndex + 1; i < selection.Length; i++, j++ )
newSelection[j] = selection[i];
}
Selection.objects = newSelection;
selection = pingTarget = null;
return;
}
}
// Ping an object in either Project view or Hierarchy view
public static Object PingInEditor( this Object obj )
{
if( obj is Component )
obj = ( (Component) obj ).gameObject;
Object selection = obj;
selection = pingTarget = obj;
// Pinging a prefab only works if the pinged object is the root of the prefab
// or a direct child of it. Pinging any grandchildren of the prefab
// does not work; in which case, traverse the parent hierarchy until
// a pingable parent is reached
if( obj.IsAsset() && obj is GameObject )
if( obj.IsAsset() )
{
#if UNITY_2018_3_OR_NEWER
Transform objTR = ( (GameObject) obj ).transform.root;
PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject );
if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant )
if( obj is GameObject )
{
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
var openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath )
// Pinging a prefab only works if the pinged object is the root of the prefab or a direct child of it. Pinging any grandchildren
// of the prefab doesn't work; in which case, traverse the parent hierarchy until a pingable parent is reached
Transform objTR = ( (GameObject) obj ).transform.root;
PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject );
if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant )
{
// Ping the object in prefab stage
Transform targetParent = objTR;
Transform selectedObject = ( (GameObject) obj ).transform;
objTR = openPrefabStage.prefabContentsRoot.transform;
while( targetParent != selectedObject )
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath )
{
Transform temp = selectedObject;
while( temp.parent != targetParent )
temp = temp.parent;
objTR = objTR.GetChild( temp.GetSiblingIndex() );
targetParent = temp;
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot );
if( prefabStageGO != null )
{
objTR = prefabStageGO.transform;
selection = objTR.gameObject;
}
}
selection = objTR.gameObject;
else if( obj != objTR.gameObject )
selection = objTR.gameObject;
}
#if UNITY_2019_1_OR_NEWER
else if( obj != objTR.gameObject )
else if( prefabAssetType == PrefabAssetType.Model )
{
Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name );
selection = objTR.gameObject;
objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
}
#else
else
Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name );
#endif
}
#else
Transform objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
#endif
obj = objTR.gameObject;
pingTarget = objTR.gameObject;
}
else if( ( obj.hideFlags & ( HideFlags.HideInInspector | HideFlags.HideInHierarchy ) ) != HideFlags.None )
{
// 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 ) );
}
}
}
// 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 = thisRoot.transform;
Transform root2 = symmetricRoot.transform;
while( root1 != target )
{
Transform temp = target;
while( temp.parent != root1 )
temp = temp.parent;
Transform newRoot2;
int siblingIndex = temp.GetSiblingIndex();
if( siblingIndex < root2.childCount )
{
newRoot2 = root2.GetChild( siblingIndex );
if( newRoot2.name != temp.name )
newRoot2 = root2.Find( temp.name );
}
else
newRoot2 = root2.Find( temp.name );
if( newRoot2 == null )
return null;
root2 = newRoot2;
root1 = temp;
}
EditorGUIUtility.PingObject( obj );
return selection;
return root2.gameObject;
}
// Returns -1 if t1 is above t2 in Hierarchy, 1 if t1 is below t2 in Hierarchy and 0 if they are the same object
public static int CompareHierarchySiblingIndices( Transform t1, Transform t2 )
{
Transform parent1 = t1.parent;
Transform parent2 = t2.parent;
if( parent1 == parent2 )
return t1.GetSiblingIndex() - t2.GetSiblingIndex();
int deltaHierarchyDepth = 0;
for( ; parent1; parent1 = parent1.parent )
deltaHierarchyDepth++;
for( ; parent2; parent2 = parent2.parent )
deltaHierarchyDepth--;
for( ; deltaHierarchyDepth > 0; deltaHierarchyDepth-- )
{
t1 = t1.parent;
if( t1 == t2 )
return 1;
}
for( ; deltaHierarchyDepth < 0; deltaHierarchyDepth++ )
{
t2 = t2.parent;
if( t1 == t2 )
return -1;
}
while( t1.parent != t2.parent )
{
t1 = t1.parent;
t2 = t2.parent;
}
return t1.GetSiblingIndex() - t2.GetSiblingIndex();
}
// 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;
// SerializeReference makes even System.Object fields serializable
if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) )
return true;
if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) )
return false;
return IsTypeSerializable( fieldInfo.FieldType );
@@ -289,25 +369,38 @@ namespace AssetUsageDetectorNamespace.Extras
}
else if( type.IsGenericType )
{
if( type.GetGenericTypeDefinition() != typeof( List<> ) )
return false;
// Generic types are allowed on 2020.1 and later
if( type.GetGenericTypeDefinition() == typeof( List<> ) )
{
type = type.GetGenericArguments()[0];
type = type.GetGenericArguments()[0];
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
}
if( type.IsGenericType )
return false;
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;
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
if( type.Namespace == nativeCollectionsNamespace )
return true;
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
return true;
// Searching pointers or ref variables for reference throws ArgumentException
if( type.IsPointer || type.IsByRef )
return true;
return false;
}
// Get <get> function for a field
@@ -334,7 +427,20 @@ namespace AssetUsageDetectorNamespace.Extras
{
// Can't use PropertyWrapper (which uses CreateDelegate) for property getters of structs
if( propertyInfo.DeclaringType.IsValueType )
return propertyInfo.CanRead ? ( ( obj ) => propertyInfo.GetValue( obj, null ) ) : (VariableGetVal) null;
{
return !propertyInfo.CanRead ? (VariableGetVal) null : ( obj ) =>
{
try
{
return propertyInfo.GetValue( obj, null );
}
catch
{
// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
return null;
}
};
}
Type GenType = typeof( PropertyWrapper<,> ).MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType );
return ( (IPropertyAccessor) Activator.CreateInstance( GenType, propertyInfo.GetGetMethod( true ) ) ).GetValue;
@@ -343,9 +449,9 @@ namespace AssetUsageDetectorNamespace.Extras
// 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;
}
@@ -353,6 +459,63 @@ 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 header inside OnGUI
public static void DrawHeader( string label )
{
Color c = GUI.backgroundColor;
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
GUILayout.Box( label, BoxGUIStyle, GL_EXPAND_WIDTH );
GUI.backgroundColor = c;
}
// Draw horizontal line inside OnGUI
public static void DrawSeparatorLine()
{
GUILayout.Space( 4f );
GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH );
GUILayout.Space( 4f );
}
/// <summary>
/// Restricts the given Rect within the screen's bounds.
/// </summary>
public static Rect GetScreenFittedRect(Rect originalRect, EditorWindow editorWindow)
{
screenFittedRectGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.ContainerWindow").GetMethod("FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (screenFittedRectGetter.GetParameters().Length == 3)
return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, true, true });
else
{
// New version introduced in Unity 2022.3.62f1, Unity 6.0.49f1 and Unity 6.1.0f1.
// Usage example: https://github.com/Unity-Technologies/UnityCsReference/blob/10f8718268a7e34844ba7d59792117c28d75a99b/Editor/Mono/EditorWindow.cs#L1264
editorWindowHostViewGetter ??= typeof(EditorWindow).GetField("m_Parent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
hostViewContainerWindowGetter ??= typeof(EditorWindow).Assembly.GetType("UnityEditor.HostView").GetProperty("window", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (Rect)screenFittedRectGetter.Invoke(null, new object[] { originalRect, originalRect.center, true, hostViewContainerWindowGetter.GetValue(editorWindowHostViewGetter.GetValue(editorWindow), null) });
}
}
// Check if all the objects inside the list are null
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
{
@@ -361,7 +524,7 @@ namespace AssetUsageDetectorNamespace.Extras
for( int i = 0; i < objectsToSearch.Count; i++ )
{
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) )
if( objectsToSearch[i].obj != null )
return false;
}
@@ -369,36 +532,47 @@ namespace AssetUsageDetectorNamespace.Extras
}
// Check if all the objects inside the list are null
public static bool IsEmpty( this List<Object> objects )
public static bool IsEmpty<T>( this List<T> objects ) where T : Object
{
if( objects == null )
return true;
for( int i = 0; i < objects.Count; i++ )
{
if( objects[i] != null && !objects[i].Equals( null ) )
if( objects[i] != null )
return false;
}
return true;
}
// Check if all the objects that are enumerated are null
public static bool IsEmpty( this IEnumerable<Object> objects )
// Returns true is str starts with prefix
public static bool StartsWithFast( this string str, string prefix )
{
if( objects == null )
return true;
using( IEnumerator<Object> enumerator = objects.GetEnumerator() )
int aLen = str.Length;
int bLen = prefix.Length;
int ap = 0; int bp = 0;
while( ap < aLen && bp < bLen && str[ap] == prefix[bp] )
{
while( enumerator.MoveNext() )
{
if( enumerator.Current != null && !enumerator.Current.Equals( null ) )
return false;
}
ap++;
bp++;
}
return true;
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 )
@@ -422,13 +596,5 @@ namespace AssetUsageDetectorNamespace.Extras
return false;
}
public static void RemoveAtFast<T>( this List<T> list, int index )
{
int lastElementIndex = list.Count - 1;
list[index] = list[lastElementIndex];
list.RemoveAt( lastElementIndex );
}
}
}
@@ -1,38 +1,53 @@
using System;
using System.Reflection;
using System.Text;
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 );
// Custom struct to hold a variable, its important properties and its getter function
public struct VariableGetterHolder
public readonly struct VariableGetterHolder
{
public readonly string name;
public readonly bool isProperty;
public readonly MemberInfo variable;
public readonly bool isSerializable;
private readonly VariableGetVal getter;
public readonly string Name { get { return variable.Name; } }
public readonly 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;
}
public object Get( object obj )
public readonly object Get( object obj )
{
return getter( obj );
try
{
return getter( obj );
}
catch( Exception 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;
}
}
}
@@ -60,8 +75,7 @@ namespace AssetUsageDetectorNamespace.Extras
}
catch
{
// Property getters may return various kinds of exceptions
// if their backing fields are not initialized (yet)
// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
return null;
}
}
+3 -14
View File
@@ -1,15 +1,4 @@
= Asset Usage Detector =
= Asset Usage Detector (v2.5.7) =
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
1. ABOUT
This tool helps you find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. lists the objects that refer to them.
2. HOW TO
Open "Window-Asset Usage Detector" window, configure the settings and hit GO! You can also use the "Assets-Search For References" shortcut to find the selected object(s)' references.
3. KNOWN LIMITATIONS
- static variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
-34
View File
@@ -1,34 +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, use the **Assets - Search For References** shortcut to find the selected object(s)' references
**NOTE:** If your project uses an older version of AssetUsageDetector, delete the older version before updating the plugin.
### C. FEATURES
- You can search for references of any object that extends *UnityEngine.Object*
- Seaches every corner of your project with its *reflection* based search algorithm (even non-Unity objects, structs and data types like dictionaries are searched)
- 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
+9
View File
@@ -0,0 +1,9 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "2.5.7",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",
"description": "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. 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:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB