Compare commits
95 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b0bf247aa4 | |||
| 4e4321bdae | |||
| 69f7ee5a27 | |||
| afda67474b | |||
| 955972cc00 | |||
| ac55f29e7d | |||
| 8f8316266c | |||
| 6edf344ebc | |||
| e80ad3b905 | |||
| 0342ab20c9 | |||
| 6a158cba7e | |||
| 652dbe2171 | |||
| a1b66ced77 | |||
| 2bd6a02504 | |||
| 790a508dcd | |||
| d6a03aa8f2 | |||
| 177db66fbd | |||
| 4415d4b6f4 | |||
| 5104901c5d | |||
| 962f6e04d4 | |||
| 204de979ba | |||
| 50ce6f56c9 | |||
| 0f872ef04d | |||
| f68c8a1375 | |||
| ecfb1adf88 | |||
| e63ebd7f85 | |||
| d5b082c093 | |||
| 1faa789f48 | |||
| 610fffc763 | |||
| 9fddcab6fa | |||
| 66dd66787c | |||
| da921c2e06 | |||
| d9cc52cc37 | |||
| e6641bef48 | |||
| a6d91a58a3 | |||
| ace8ac4947 | |||
| 02167c28a2 | |||
| 092b80ba29 | |||
| 524965aee7 | |||
| efad9fa158 | |||
| 6cd2b407cc | |||
| 3c4292159a | |||
| 1a2eba24bd | |||
| cf0fea56ab | |||
| 956aea1ced | |||
| 466a152ba6 | |||
| 5eda0c1cb0 | |||
| 42e3278129 | |||
| f6a999f053 | |||
| 8441e4701c | |||
| d57a707678 | |||
| 3fa3344507 | |||
| 8072530c2c | |||
| 28a73e2843 | |||
| c7e52466ef | |||
| 875f3e6794 | |||
| 635d0653fa | |||
| cb4454b493 | |||
| dfb8541605 | |||
| 4b146280ab | |||
| 8a6fe822d6 | |||
| c9ceab6085 | |||
| 4fddcb7b80 | |||
| 001df6eb6c | |||
| 60f8d30810 | |||
| c9dbd2d201 | |||
| 6939dbc088 | |||
| dd922e85e4 | |||
| 9648f856d1 | |||
| f724dd2fdb | |||
| 7b3b7957d8 | |||
| d5942a66c4 | |||
| dcc5d5e0ad | |||
| 8872a0fcc5 | |||
| 8c04db9b25 | |||
| b7b6f8815e | |||
| 40a28f5961 | |||
| b535e09ba2 | |||
| 499e4bc43e | |||
| 93c955993a | |||
| 21f8daffde | |||
| 8cc7798f17 | |||
| 45b0f6f1d9 | |||
| c599ea6273 | |||
| 7ba33e2d4e | |||
| ac294324dd | |||
| 8dc7d5508b | |||
| c9131811e2 | |||
| 133b8b1227 | |||
| 1db9dbf9b0 | |||
| a6b0f5ae92 | |||
| 8e7369e44e | |||
| 7b60eeacf7 | |||
| b8470536b9 | |||
| 1bebc8691d |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 83 KiB |
@@ -1,16 +1,18 @@
|
|||||||
# Asset Usage Detector for Unity 3D
|
# Asset Usage Detector for Unity 3D
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
**Available on Asset Store:** https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837
|
**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/
|
**Forum Thread:** https://forum.unity.com/threads/asset-usage-detector-find-references-to-an-asset-object-open-source.408134/
|
||||||
|
|
||||||
**[Support the Developer ☕](https://yasirkula.itch.io/unity3d)**
|
**Discord:** https://discord.gg/UJJt549AaV
|
||||||
|
|
||||||
|
**[GitHub Sponsors ☕](https://github.com/sponsors/yasirkula)**
|
||||||
|
|
||||||
## ABOUT
|
## 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!
|
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
|
## INSTALLATION
|
||||||
|
|
||||||
@@ -19,8 +21,8 @@ There are 5 ways to install this plugin:
|
|||||||
- import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package*
|
- import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) via *Assets-Import Package*
|
||||||
- clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder
|
- clone/[download](https://github.com/yasirkula/UnityAssetUsageDetector/archive/master.zip) this repository and move the *Plugins* folder to your Unity project's *Assets* folder
|
||||||
- import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837)
|
- import it from [Asset Store](https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837)
|
||||||
- *(via Package Manager)* add the following line to *Packages/manifest.json*:
|
- *(via Package Manager)* click the + button and install the package from the following git URL:
|
||||||
- `"com.yasirkula.assetusagedetector": "https://github.com/yasirkula/UnityAssetUsageDetector.git",`
|
- `https://github.com/yasirkula/UnityAssetUsageDetector.git`
|
||||||
- *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command:
|
- *(via [OpenUPM](https://openupm.com))* after installing [openupm-cli](https://github.com/openupm/openupm-cli), run the following command:
|
||||||
- `openupm add com.yasirkula.assetusagedetector`
|
- `openupm add com.yasirkula.assetusagedetector`
|
||||||
|
|
||||||
@@ -28,19 +30,44 @@ There are 5 ways to install this plugin:
|
|||||||
|
|
||||||
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
|
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
|
||||||
- or, right click an object and select **Search For References**
|
- or, right click an object and select **Search For References**
|
||||||
- In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the references are formed. If a node's label contains text inside square brackets (e.g. *\[Child object\]*), then that text describes how that node is connected to the node to its left
|
- 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)
|
||||||
|
|
||||||
## FEATURES
|

|
||||||
|
|
||||||
- You can search for references of any object that extends *UnityEngine.Object*
|

|
||||||
- Extensive search algorithm that uses *SerializedObject* and *reflection* to find references
|
|
||||||
- Can search in multiple scenes at once
|
|
||||||
- Can show complete paths to the references or only the most relevant parts of the paths (see the demonstration below)
|
|
||||||
|
|
||||||

|
## SEARCH REFACTORING
|
||||||
|
|
||||||
|
While searching for references using the Scripting API, it's possible to get notified of the found references *during* the search (some references like *Assembly Definition File* references or *Shader Graph* references aren't supported) and in most cases, refactor them (e.g. changing all usages of a searched object with something else or *null*). Disabling *Lazy Scene Search* is recommended while using this feature and it's advised to backup your project beforehand.
|
||||||
|
|
||||||
|
To initiate a search using the Scripting API, you need to put your script either in *Editor* folder or add `AssetUsageDetector.Editor` as reference to your *Assembly Definition File*. Then, you can either create a new instance of `AssetUsageDetectorNamespace.AssetUsageDetector` object and call its `Run` method, or call the `AssetUsageDetectorNamespace.AssetUsageDetectorWindow.ShowAndSearch` method. In either case, you'll be handling the search refactoring in the **searchRefactoring** callback:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
void ReplaceFontUsages( Font from, Font to )
|
||||||
|
{
|
||||||
|
AssetUsageDetector assetUsageDetector = new AssetUsageDetector();
|
||||||
|
assetUsageDetector.Run( new AssetUsageDetector.Parameters()
|
||||||
|
{
|
||||||
|
objectsToSearch = new Object[] { from },
|
||||||
|
lazySceneSearch = false,
|
||||||
|
searchRefactoring = ( searchMatch ) =>
|
||||||
|
{
|
||||||
|
Debug.LogFormat( "Found a {0} reference from {1} to {2}", searchMatch.GetType().Name, searchMatch.Source, searchMatch.Value );
|
||||||
|
searchMatch.ChangeValue( to );
|
||||||
|
}
|
||||||
|
} );
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**NOTE:** Refactored references won't be reflected to the returned search results, old references will continue to be displayed. After saving the changes (modified scenes) and initiating another search, correct search results will be shown.
|
||||||
|
|
||||||
|
**NOTE2:** After refactoring the references, consider performing a normal search to see if all references were correctly refactored. If some references weren't refactored (even though they could've been), feel free to report it.
|
||||||
|
|
||||||
## KNOWN LIMITATIONS
|
## KNOWN LIMITATIONS
|
||||||
|
|
||||||
- *static* variables are not searched
|
- *static* variables aren't searched
|
||||||
- GUIText materials are not searched
|
- *Resources.Load* usages can't be found
|
||||||
- Textures in Lens Flare's can not be searched
|
- *ref struct*s can't be searched
|
||||||
|
- *GUIText* materials aren't searched
|
||||||
|
- Textures in *Lens Flares* can't be searched
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 103 KiB |
@@ -1,6 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "AssetUsageDetector.Editor",
|
"name": "AssetUsageDetector.Editor",
|
||||||
"references": [],
|
"rootNamespace": "",
|
||||||
|
"references": [
|
||||||
|
"Unity.Addressables",
|
||||||
|
"Unity.Addressables.Editor"
|
||||||
|
],
|
||||||
"includePlatforms": [
|
"includePlatforms": [
|
||||||
"Editor"
|
"Editor"
|
||||||
],
|
],
|
||||||
@@ -10,6 +14,17 @@
|
|||||||
"precompiledReferences": [],
|
"precompiledReferences": [],
|
||||||
"autoReferenced": true,
|
"autoReferenced": true,
|
||||||
"defineConstraints": [],
|
"defineConstraints": [],
|
||||||
"versionDefines": [],
|
"versionDefines": [
|
||||||
|
{
|
||||||
|
"name": "com.unity.addressables",
|
||||||
|
"expression": "0.0.0",
|
||||||
|
"define": "ASSET_USAGE_ADDRESSABLES"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.unity.visualeffectgraph",
|
||||||
|
"expression": "0.0.0",
|
||||||
|
"define": "ASSET_USAGE_VFX_GRAPH"
|
||||||
|
}
|
||||||
|
],
|
||||||
"noEngineReferences": false
|
"noEngineReferences": false
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
|
|
||||||
|
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine.SceneManagement;
|
using UnityEngine.SceneManagement;
|
||||||
@@ -10,16 +8,16 @@ using System;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2018_3_OR_NEWER
|
#if UNITY_6000_3_OR_NEWER
|
||||||
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
|
using EntityId = UnityEngine.EntityId;
|
||||||
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
|
#else
|
||||||
|
using EntityId = System.Int32;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace AssetUsageDetectorNamespace
|
namespace AssetUsageDetectorNamespace
|
||||||
{
|
{
|
||||||
[Flags]
|
[Flags]
|
||||||
public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 };
|
public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 };
|
||||||
public enum PathDrawingMode { Full = 0, ShortRelevantParts = 1, Shortest = 2 };
|
|
||||||
|
|
||||||
public partial class AssetUsageDetector
|
public partial class AssetUsageDetector
|
||||||
{
|
{
|
||||||
@@ -32,24 +30,35 @@ namespace AssetUsageDetectorNamespace
|
|||||||
public SceneSearchMode searchInScenes = SceneSearchMode.AllScenes;
|
public SceneSearchMode searchInScenes = SceneSearchMode.AllScenes;
|
||||||
public Object[] searchInScenesSubset = null;
|
public Object[] searchInScenesSubset = null;
|
||||||
public Object[] excludedScenesFromSearch = null;
|
public Object[] excludedScenesFromSearch = null;
|
||||||
|
public bool searchInSceneLightingSettings = true;
|
||||||
public bool searchInAssetsFolder = true;
|
public bool searchInAssetsFolder = true;
|
||||||
public Object[] searchInAssetsSubset = null;
|
public Object[] searchInAssetsSubset = null;
|
||||||
public Object[] excludedAssetsFromSearch = null;
|
public Object[] excludedAssetsFromSearch = null;
|
||||||
public bool dontSearchInSourceAssets = true;
|
public bool dontSearchInSourceAssets = true;
|
||||||
public bool searchInProjectSettings = true;
|
public bool searchInProjectSettings = true;
|
||||||
|
|
||||||
public int searchDepthLimit = 4;
|
public int searchDepthLimit = 32;
|
||||||
public BindingFlags fieldModifiers = BindingFlags.Public | BindingFlags.NonPublic;
|
|
||||||
public BindingFlags propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic;
|
|
||||||
public bool searchNonSerializableVariables = true;
|
|
||||||
|
|
||||||
public bool lazySceneSearch = false;
|
public bool searchUnusedMaterialProperties = true;
|
||||||
|
|
||||||
|
public SearchRefactoring searchRefactoring = null;
|
||||||
|
|
||||||
|
public bool lazySceneSearch = true;
|
||||||
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
public bool addressablesSupport = false;
|
||||||
|
#endif
|
||||||
|
public bool calculateUnusedObjects = false;
|
||||||
|
public bool hideDuplicateRows = true;
|
||||||
|
public bool hideRedundantPrefabReferencesInAssets = false;
|
||||||
|
public bool hideRedundantPrefabReferencesInScenes = false;
|
||||||
public bool noAssetDatabaseChanges = false;
|
public bool noAssetDatabaseChanges = false;
|
||||||
public bool showDetailedProgressBar = false;
|
public bool showDetailedProgressBar = true;
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
// A set that contains the searched asset(s) and their sub-assets (if any)
|
private Parameters searchParameters;
|
||||||
|
|
||||||
|
// A set that contains the searched scene object(s), asset(s) and their sub-assets (if any)
|
||||||
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
|
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
|
||||||
// Scenes of scene object(s) in objectsToSearchSet
|
// Scenes of scene object(s) in objectsToSearchSet
|
||||||
private readonly HashSet<string> sceneObjectsToSearchScenesSet = new HashSet<string>();
|
private readonly HashSet<string> sceneObjectsToSearchScenesSet = new HashSet<string>();
|
||||||
@@ -68,27 +77,20 @@ namespace AssetUsageDetectorNamespace
|
|||||||
private SearchResultGroup currentSearchResultGroup;
|
private SearchResultGroup currentSearchResultGroup;
|
||||||
|
|
||||||
// An optimization to search an object only once (key is a hash of the searched object)
|
// An optimization to search an object only once (key is a hash of the searched object)
|
||||||
private readonly Dictionary<string, ReferenceNode> searchedObjects = new Dictionary<string, ReferenceNode>( 32768 );
|
private readonly Dictionary<string, ReferenceNode> searchedObjects = new Dictionary<string, ReferenceNode>( 4096 );
|
||||||
|
private readonly Dictionary<EntityId, ReferenceNode> searchedUnityObjects = new(32768); // Unity objects use their EntityIds as key
|
||||||
|
|
||||||
// Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
|
// Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
|
||||||
private readonly List<object> callStack = new List<object>( 64 );
|
private readonly List<object> callStack = new List<object>( 64 );
|
||||||
|
|
||||||
private int searchDepthLimit; // Depth limit for recursively searching variables of objects
|
|
||||||
|
|
||||||
private Object currentSearchedObject;
|
private Object currentSearchedObject;
|
||||||
private int currentDepth;
|
|
||||||
|
|
||||||
private bool dontSearchInSourceAssets;
|
|
||||||
private bool searchingSourceAssets;
|
private bool searchingSourceAssets;
|
||||||
private bool isInPlayMode;
|
private bool isInPlayMode;
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
private PrefabStage openPrefabStage;
|
private PrefabStage openPrefabStage;
|
||||||
private GameObject openPrefabStagePrefabAsset;
|
private GameObject openPrefabStagePrefabAsset;
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
private GameObject openPrefabStageContextObject;
|
private GameObject openPrefabStageContextObject;
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
private int searchedObjectsCount; // Number of searched objects
|
private int searchedObjectsCount; // Number of searched objects
|
||||||
private double searchStartTime;
|
private double searchStartTime;
|
||||||
@@ -100,27 +102,16 @@ namespace AssetUsageDetectorNamespace
|
|||||||
{
|
{
|
||||||
if( searchParameters == null )
|
if( searchParameters == null )
|
||||||
{
|
{
|
||||||
Debug.LogError( "searchParameters must not be null!" );
|
Debug.LogError( "'searchParameters' mustn't be null!" );
|
||||||
return new SearchResult( false, null, null, this, searchParameters );
|
return new SearchResult( false, null, null, null, this, searchParameters );
|
||||||
}
|
}
|
||||||
|
|
||||||
if( searchParameters.objectsToSearch == null )
|
if( searchParameters.objectsToSearch == null )
|
||||||
{
|
{
|
||||||
Debug.LogError( "objectsToSearch list is empty!" );
|
Debug.LogError( "'objectsToSearch' list (\"SEARCHED OBJECTS\") is empty!" );
|
||||||
return new SearchResult( false, null, null, this, searchParameters );
|
return new SearchResult( false, null, null, null, this, searchParameters );
|
||||||
}
|
}
|
||||||
|
|
||||||
if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
|
|
||||||
{
|
|
||||||
// Don't start the search if at least one scene is currently dirty (not saved)
|
|
||||||
Debug.LogError( "Save open scenes first!" );
|
|
||||||
return new SearchResult( false, null, null, this, searchParameters );
|
|
||||||
}
|
|
||||||
|
|
||||||
List<SearchResultGroup> searchResult = null;
|
|
||||||
|
|
||||||
isInPlayMode = EditorApplication.isPlaying;
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
openPrefabStagePrefabAsset = null;
|
openPrefabStagePrefabAsset = null;
|
||||||
string openPrefabStageAssetPath = null;
|
string openPrefabStageAssetPath = null;
|
||||||
openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
|
openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
|
||||||
@@ -133,45 +124,46 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( openPrefabStage.scene.isDirty )
|
if( openPrefabStage.scene.isDirty )
|
||||||
{
|
{
|
||||||
// Don't start the search if a prefab stage is currently open and dirty (not saved)
|
// Don't start the search if a prefab stage is currently open and dirty (not saved)
|
||||||
Debug.LogError( "Save open prefabs first!" );
|
Debug.LogError( "Save open prefab first!" );
|
||||||
return new SearchResult( false, null, null, this, searchParameters );
|
return new SearchResult( false, null, null, null, this, searchParameters );
|
||||||
}
|
}
|
||||||
|
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
string prefabAssetPath = openPrefabStage.assetPath;
|
string prefabAssetPath = openPrefabStage.assetPath;
|
||||||
#else
|
|
||||||
string prefabAssetPath = openPrefabStage.prefabAssetPath;
|
|
||||||
#endif
|
|
||||||
openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabAssetPath );
|
openPrefabStagePrefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabAssetPath );
|
||||||
openPrefabStageAssetPath = prefabAssetPath;
|
openPrefabStageAssetPath = prefabAssetPath;
|
||||||
|
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
openPrefabStageContextObject = openPrefabStage.openedFromInstanceRoot;
|
openPrefabStageContextObject = openPrefabStage.openedFromInstanceRoot;
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
List<SearchResultGroup> searchResult = null;
|
||||||
|
isInPlayMode = EditorApplication.isPlaying;
|
||||||
|
|
||||||
|
if( !isInPlayMode && !Utilities.AreScenesSaved() && !EditorUtility.DisplayDialog( "Asset Usage Detector", "Some scene(s) aren't saved. This may result in incorrect search results in those scene(s). Proceed?", "Yes", "Cancel" ) )
|
||||||
|
{
|
||||||
|
Debug.LogError( "Save open scene(s) first!" );
|
||||||
|
return new SearchResult( false, null, null, null, this, searchParameters );
|
||||||
|
}
|
||||||
|
|
||||||
// Get the scenes that are open right now
|
// Get the scenes that are open right now
|
||||||
SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null;
|
SceneSetup[] initialSceneSetup = !isInPlayMode ? EditorSceneManager.GetSceneManagerSetup() : null;
|
||||||
|
Scene activeScene = EditorSceneManager.GetActiveScene();
|
||||||
|
|
||||||
// Make sure that the AssetDatabase is up-to-date
|
// Make sure that the AssetDatabase is up-to-date
|
||||||
AssetDatabase.SaveAssets();
|
AssetDatabase.SaveAssets();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
this.searchParameters = searchParameters;
|
||||||
|
|
||||||
// Initialize commonly used variables
|
// Initialize commonly used variables
|
||||||
searchResult = new List<SearchResultGroup>(); // Overall search results
|
searchResult = new List<SearchResultGroup>(); // Overall search results
|
||||||
|
|
||||||
currentSearchedObject = null;
|
currentSearchedObject = null;
|
||||||
currentDepth = 0;
|
|
||||||
searchedObjectsCount = 0;
|
searchedObjectsCount = 0;
|
||||||
searchStartTime = EditorApplication.timeSinceStartup;
|
searchStartTime = EditorApplication.timeSinceStartup;
|
||||||
|
|
||||||
searchDepthLimit = searchParameters.searchDepthLimit;
|
|
||||||
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
|
|
||||||
|
|
||||||
searchedObjects.Clear();
|
searchedObjects.Clear();
|
||||||
|
searchedUnityObjects.Clear();
|
||||||
animationClipUniqueBindings.Clear();
|
animationClipUniqueBindings.Clear();
|
||||||
callStack.Clear();
|
callStack.Clear();
|
||||||
objectsToSearchSet.Clear();
|
objectsToSearchSet.Clear();
|
||||||
@@ -182,9 +174,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
excludedAssetsPathsSet.Clear();
|
excludedAssetsPathsSet.Clear();
|
||||||
alwaysSearchedExtensionsSet.Clear();
|
alwaysSearchedExtensionsSet.Clear();
|
||||||
shaderIncludesToSearchSet.Clear();
|
shaderIncludesToSearchSet.Clear();
|
||||||
#if UNITY_2017_3_OR_NEWER
|
|
||||||
assemblyDefinitionFilesToSearch.Clear();
|
assemblyDefinitionFilesToSearch.Clear();
|
||||||
#endif
|
|
||||||
|
|
||||||
if( assetDependencyCache == null )
|
if( assetDependencyCache == null )
|
||||||
{
|
{
|
||||||
@@ -281,10 +271,10 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes )
|
if( ( searchParameters.searchInScenes & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes )
|
||||||
{
|
{
|
||||||
// Get all open (and loaded) scenes
|
// Get all open (and loaded) scenes
|
||||||
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
|
for( int i = 0; i < SceneManager.sceneCount; i++ )
|
||||||
{
|
{
|
||||||
Scene scene = EditorSceneManager.GetSceneAt( i );
|
Scene scene = SceneManager.GetSceneAt( i );
|
||||||
if( scene.IsValid() )
|
if( scene.IsValid() && scene.isLoaded )
|
||||||
scenesToSearch.Add( scene.path );
|
scenesToSearch.Add( scene.path );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,31 +296,43 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( isInPlayMode )
|
if( isInPlayMode )
|
||||||
{
|
{
|
||||||
HashSet<string> openScenes = new HashSet<string>();
|
HashSet<string> openScenes = new HashSet<string>();
|
||||||
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
|
for( int i = 0; i < SceneManager.sceneCount; i++ )
|
||||||
{
|
{
|
||||||
Scene scene = EditorSceneManager.GetSceneAt( i );
|
Scene scene = SceneManager.GetSceneAt( i );
|
||||||
if( scene.IsValid() )
|
if( scene.IsValid() && scene.isLoaded )
|
||||||
openScenes.Add( scene.path );
|
openScenes.Add( scene.path );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<string> skippedScenes = new List<string>( scenesToSearch.Count );
|
||||||
scenesToSearch.RemoveWhere( ( path ) =>
|
scenesToSearch.RemoveWhere( ( path ) =>
|
||||||
{
|
{
|
||||||
if( !openScenes.Contains( path ) )
|
if( !openScenes.Contains( path ) )
|
||||||
{
|
{
|
||||||
Debug.Log( "Can't search unloaded scenes while in play mode, skipped " + path );
|
skippedScenes.Add( path );
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
} );
|
} );
|
||||||
|
|
||||||
|
if( skippedScenes.Count > 0 )
|
||||||
|
{
|
||||||
|
StringBuilder sb = Utilities.stringBuilder;
|
||||||
|
sb.Length = 0;
|
||||||
|
sb.Append( "Can't search unloaded scenes while in play mode, skipped " ).Append( skippedScenes.Count ).AppendLine( " scene(s):" );
|
||||||
|
for( int i = 0; i < skippedScenes.Count; i++ )
|
||||||
|
sb.Append( "- " ).AppendLine( skippedScenes[i] );
|
||||||
|
|
||||||
|
Debug.Log( sb.ToString() );
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize data used by search functions
|
// Initialize data used by search functions
|
||||||
InitializeSearchFunctionsData( searchParameters );
|
InitializeSearchFunctionsData( searchParameters );
|
||||||
|
|
||||||
// Initialize the nodes of searched asset(s)
|
// Initialize the nodes of searched asset(s)
|
||||||
foreach( Object obj in objectsToSearchSet )
|
foreach (Object obj in objectsToSearchSet)
|
||||||
searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) );
|
searchedUnityObjects.Add(obj.GetEntityId(), PopReferenceNode(obj));
|
||||||
|
|
||||||
// Progressbar values
|
// Progressbar values
|
||||||
int searchProgress = 0;
|
int searchProgress = 0;
|
||||||
@@ -431,7 +433,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If a reference is found in the Project view, save the results
|
// If a reference is found in the Project view, save the results
|
||||||
if( currentSearchResultGroup.NumberOfReferences > 0 )
|
if( currentSearchResultGroup.AnyReferencesFound )
|
||||||
searchResult.Add( currentSearchResultGroup );
|
searchResult.Add( currentSearchResultGroup );
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -456,14 +458,10 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if( currentSearchResultGroup.NumberOfReferences > 0 )
|
if( currentSearchResultGroup.AnyReferencesFound )
|
||||||
searchResult.Add( currentSearchResultGroup );
|
searchResult.Add( currentSearchResultGroup );
|
||||||
}
|
}
|
||||||
|
|
||||||
// Search non-serializable variables for references while searching a scene in play mode
|
|
||||||
if( isInPlayMode )
|
|
||||||
searchSerializableVariablesOnly = false;
|
|
||||||
|
|
||||||
if( scenesToSearch.Count > 0 )
|
if( scenesToSearch.Count > 0 )
|
||||||
{
|
{
|
||||||
// Calculate the path(s) of the scenes that won't be searched for references
|
// Calculate the path(s) of the scenes that won't be searched for references
|
||||||
@@ -492,19 +490,28 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Search scenes for references
|
||||||
foreach( string scenePath in scenesToSearch )
|
foreach( string scenePath in scenesToSearch )
|
||||||
{
|
{
|
||||||
if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) )
|
if( EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) )
|
||||||
throw new Exception( "Search aborted" );
|
throw new Exception( "Search aborted" );
|
||||||
|
|
||||||
// Search scene for references
|
|
||||||
if( string.IsNullOrEmpty( scenePath ) )
|
if( string.IsNullOrEmpty( scenePath ) )
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if( excludedScenesPathsSet.Contains( scenePath ) )
|
if( excludedScenesPathsSet.Contains( scenePath ) )
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
SearchScene( scenePath, searchResult, searchParameters.lazySceneSearch, initialSceneSetup );
|
// Skip scenes in read-only packages (Issue #36)
|
||||||
|
// Credit: https://forum.unity.com/threads/check-if-asset-inside-package-is-readonly.900902/#post-5990822
|
||||||
|
if( !scenePath.StartsWithFast( "Assets/" ) )
|
||||||
|
{
|
||||||
|
var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath( scenePath );
|
||||||
|
if( packageInfo != null && packageInfo.source != UnityEditor.PackageManager.PackageSource.Embedded && packageInfo.source != UnityEditor.PackageManager.PackageSource.Local )
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
SearchScene( scenePath, searchResult, searchParameters, initialSceneSetup );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,12 +527,12 @@ namespace AssetUsageDetectorNamespace
|
|||||||
for( int i = 0; i < rootGameObjects.Length; i++ )
|
for( int i = 0; i < rootGameObjects.Length; i++ )
|
||||||
SearchGameObjectRecursively( rootGameObjects[i] );
|
SearchGameObjectRecursively( rootGameObjects[i] );
|
||||||
|
|
||||||
if( currentSearchResultGroup.NumberOfReferences > 0 )
|
if( currentSearchResultGroup.AnyReferencesFound )
|
||||||
searchResult.Add( currentSearchResultGroup );
|
searchResult.Add( currentSearchResultGroup );
|
||||||
}
|
}
|
||||||
|
|
||||||
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
|
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
|
||||||
if( !dontSearchInSourceAssets )
|
if( !searchParameters.dontSearchInSourceAssets )
|
||||||
{
|
{
|
||||||
searchingSourceAssets = true;
|
searchingSourceAssets = true;
|
||||||
|
|
||||||
@@ -538,54 +545,28 @@ namespace AssetUsageDetectorNamespace
|
|||||||
searchingSourceAssets = false;
|
searchingSourceAssets = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
EditorUtility.DisplayProgressBar( "Please wait...", "Post-processing search results", 1f );
|
||||||
|
|
||||||
InitializeSearchResultNodes( searchResult );
|
InitializeSearchResultNodes( searchResult );
|
||||||
|
|
||||||
|
HashSet<Object> usedObjects = null;
|
||||||
|
if( searchResult.Count > 0 && searchParameters.calculateUnusedObjects )
|
||||||
|
CalculateUnusedObjects( searchResult, out usedObjects );
|
||||||
|
|
||||||
// Log some c00l stuff to console
|
// Log some c00l stuff to console
|
||||||
Debug.Log( "Searched " + searchedObjectsCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" );
|
Debug.Log( "Searched " + searchedObjectsCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" );
|
||||||
|
|
||||||
return new SearchResult( true, searchResult, initialSceneSetup, this, searchParameters );
|
return new SearchResult( true, searchResult, usedObjects, initialSceneSetup, this, searchParameters );
|
||||||
}
|
}
|
||||||
catch( Exception e )
|
catch( Exception e )
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 );
|
StringBuilder sb = Utilities.stringBuilder;
|
||||||
sb.AppendLine( "<b>AssetUsageDetector Error:</b>" ).AppendLine().Append( e ).AppendLine();
|
sb.Length = 0;
|
||||||
|
sb.EnsureCapacity( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 );
|
||||||
|
|
||||||
Object latestUnityObjectInCallStack = null;
|
sb.AppendLine( "<b>AssetUsageDetector Error:</b> The following Exception is thrown during the search. Details:" );
|
||||||
if( callStack.Count > 0 )
|
|
||||||
{
|
|
||||||
sb.AppendLine( "Stack contents: " );
|
|
||||||
|
|
||||||
for( int i = callStack.Count - 1; i >= 0; i-- )
|
Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb );
|
||||||
{
|
|
||||||
latestUnityObjectInCallStack = callStack[i] as Object;
|
|
||||||
if( latestUnityObjectInCallStack )
|
|
||||||
{
|
|
||||||
if( !AssetDatabase.Contains( latestUnityObjectInCallStack ) )
|
|
||||||
{
|
|
||||||
string scenePath = AssetDatabase.GetAssetOrScenePath( latestUnityObjectInCallStack );
|
|
||||||
if( !string.IsNullOrEmpty( scenePath ) && SceneManager.GetSceneByPath( scenePath ).IsValid() )
|
|
||||||
sb.Append( "Scene: " ).AppendLine( scenePath );
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for( int i = callStack.Count - 1; i >= 0; i-- )
|
|
||||||
{
|
|
||||||
sb.Append( i ).Append( ": " );
|
|
||||||
|
|
||||||
Object unityObject = callStack[i] as Object;
|
|
||||||
if( unityObject )
|
|
||||||
sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" );
|
|
||||||
else if( callStack[i] != null )
|
|
||||||
sb.Append( callStack[i].GetType() ).AppendLine( " object" );
|
|
||||||
else
|
|
||||||
sb.AppendLine( "<<destroyed>>" );
|
|
||||||
}
|
|
||||||
|
|
||||||
sb.AppendLine();
|
|
||||||
}
|
|
||||||
|
|
||||||
sb.AppendLine( "Searching references of: " );
|
sb.AppendLine( "Searching references of: " );
|
||||||
foreach( Object obj in objectsToSearchSet )
|
foreach( Object obj in objectsToSearchSet )
|
||||||
@@ -595,6 +576,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
Debug.LogError( sb.ToString(), latestUnityObjectInCallStack );
|
Debug.LogError( sb.ToString(), latestUnityObjectInCallStack );
|
||||||
|
Debug.LogException( e, latestUnityObjectInCallStack );
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -603,7 +585,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
catch
|
catch
|
||||||
{ }
|
{ }
|
||||||
|
|
||||||
return new SearchResult( false, searchResult, initialSceneSetup, this, searchParameters );
|
return new SearchResult( false, searchResult, null, initialSceneSetup, this, searchParameters );
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -612,11 +594,13 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
EditorUtility.ClearProgressBar();
|
EditorUtility.ClearProgressBar();
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
// If the active scene was changed during search, reset it
|
||||||
|
if( EditorSceneManager.GetActiveScene() != activeScene )
|
||||||
|
EditorSceneManager.SetActiveScene( activeScene );
|
||||||
|
|
||||||
// If a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed
|
// If a prefab stage was open when the search was triggered, try reopening the prefab stage after the search is completed
|
||||||
if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) )
|
if( !string.IsNullOrEmpty( openPrefabStageAssetPath ) )
|
||||||
{
|
{
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
bool shouldOpenPrefabStageWithoutContext = true;
|
bool shouldOpenPrefabStageWithoutContext = true;
|
||||||
if( openPrefabStageContextObject != null && !openPrefabStageContextObject.Equals( null ) )
|
if( openPrefabStageContextObject != null && !openPrefabStageContextObject.Equals( null ) )
|
||||||
{
|
{
|
||||||
@@ -634,23 +618,181 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
if( shouldOpenPrefabStageWithoutContext )
|
if( shouldOpenPrefabStageWithoutContext )
|
||||||
#endif
|
AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) );
|
||||||
AssetDatabase.OpenAsset( AssetDatabase.LoadAssetAtPath<GameObject>( openPrefabStageAssetPath ) );
|
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void InitializeSearchResultNodes( List<SearchResultGroup> searchResult )
|
private void InitializeSearchResultNodes( List<SearchResultGroup> searchResult )
|
||||||
{
|
{
|
||||||
for( int i = 0; i < searchResult.Count; i++ )
|
for( int i = 0; i < searchResult.Count; i++ )
|
||||||
searchResult[i].InitializeNodes( GetReferenceNode );
|
|
||||||
|
|
||||||
// If there are any empty groups after node initialization, remove those groups
|
|
||||||
for( int i = searchResult.Count - 1; i >= 0; i-- )
|
|
||||||
{
|
{
|
||||||
if( !searchResult[i].PendingSearch && searchResult[i].NumberOfReferences == 0 )
|
searchResult[i].InitializeNodes( objectsToSearchSet );
|
||||||
searchResult.RemoveAtFast( i );
|
|
||||||
|
// Remove empty search result groups
|
||||||
|
if( !searchResult[i].PendingSearch && !searchResult[i].AnyReferencesFound )
|
||||||
|
searchResult.RemoveAt( i-- );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CalculateUnusedObjects( List<SearchResultGroup> searchResult, out HashSet<Object> usedObjectsSet )
|
||||||
|
{
|
||||||
|
currentSearchResultGroup = new SearchResultGroup( "Unused Objects", SearchResultGroup.GroupType.UnusedObjects, false, false );
|
||||||
|
|
||||||
|
usedObjectsSet = new HashSet<Object>();
|
||||||
|
HashSet<string> usedObjectPathsSet = new HashSet<string>(); // For assets: stores the filepaths, For scene objects: stores the topmost GameObject's instanceID
|
||||||
|
foreach( SearchResultGroup searchResultGroup in searchResult )
|
||||||
|
{
|
||||||
|
for( int j = 0; j < searchResultGroup.NumberOfReferences; j++ )
|
||||||
|
{
|
||||||
|
Object obj = searchResultGroup[j].UnityObject;
|
||||||
|
if( obj is Component )
|
||||||
|
obj = ( (Component) obj ).gameObject;
|
||||||
|
|
||||||
|
if( usedObjectsSet.Add( obj ) )
|
||||||
|
{
|
||||||
|
string assetPath = AssetDatabase.GetAssetPath( obj );
|
||||||
|
if( !string.IsNullOrEmpty( assetPath ) )
|
||||||
|
usedObjectPathsSet.Add( assetPath );
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (Transform parent = ((GameObject)obj).transform.parent; parent != null; parent = parent.parent)
|
||||||
|
usedObjectPathsSet.Add(parent.gameObject.GetEntityId().ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Dictionary<string, ReferenceNode> unusedMainObjectNodes = new Dictionary<string, ReferenceNode>( objectsToSearchSet.Count - usedObjectsSet.Count );
|
||||||
|
Dictionary<string, List<ReferenceNode>> unusedSubObjectNodes = new Dictionary<string, List<ReferenceNode>>( objectsToSearchSet.Count - usedObjectsSet.Count );
|
||||||
|
foreach( Object obj in objectsToSearchSet )
|
||||||
|
{
|
||||||
|
// Omit components, their GameObjects are already included in search
|
||||||
|
if( obj is Component )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Omit assets that are invisible in Hierarchy/Inspector
|
||||||
|
if( ( obj.hideFlags & ( HideFlags.HideInInspector | HideFlags.HideInHierarchy ) ) != HideFlags.None )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if( usedObjectsSet.Contains( obj ) )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string assetPath = AssetDatabase.GetAssetPath( obj );
|
||||||
|
|
||||||
|
// Omit unused sub-assets whose parent assets are used (configurable via Settings)
|
||||||
|
if( AssetUsageDetectorSettings.MarkUsedAssetsSubAssetsAsUsed && AssetDatabase.IsSubAsset( obj ) && usedObjectsSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Omit meshes of an imported model asset
|
||||||
|
if( obj is Mesh && !string.IsNullOrEmpty( assetPath ) && AssetDatabase.GetMainAssetTypeAtPath( assetPath ) == typeof( GameObject ) && objectsToSearchSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
// Omit MonoScripts whose types can't be determined
|
||||||
|
if( obj is MonoScript && ( (MonoScript) obj ).GetClass() == null )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
GameObject searchedTopmostGameObject = null;
|
||||||
|
if( obj is GameObject )
|
||||||
|
{
|
||||||
|
if( string.IsNullOrEmpty( assetPath ) )
|
||||||
|
{
|
||||||
|
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent )
|
||||||
|
{
|
||||||
|
if( objectsToSearchSet.Contains( parent ) && !usedObjectsSet.Contains( parent.gameObject ) )
|
||||||
|
searchedTopmostGameObject = parent.gameObject;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent )
|
||||||
|
{
|
||||||
|
if( objectsToSearchSet.Contains( parent ) )
|
||||||
|
{
|
||||||
|
searchedTopmostGameObject = parent.gameObject;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if( searchedTopmostGameObject && !string.IsNullOrEmpty( assetPath ) ) // Omit GameObject assets if their parent objects are already included in search
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use new ReferenceNodes in UnusedObjects search result group because we don't want these nodes to be linked to the actual ReferenceNodes in any way
|
||||||
|
// (i.e. we don't use actual ReferenceNodes of these objects (GetReferenceNode) because these may have links to other nodes in unknown circumstances)
|
||||||
|
ReferenceNode node = PopReferenceNode( obj );
|
||||||
|
node.usedState = ReferenceNode.UsedState.Unused;
|
||||||
|
|
||||||
|
if( string.IsNullOrEmpty( assetPath ) )
|
||||||
|
{
|
||||||
|
if( !searchedTopmostGameObject )
|
||||||
|
{
|
||||||
|
if (obj is GameObject)
|
||||||
|
unusedMainObjectNodes[obj.GetEntityId().ToString()] = node;
|
||||||
|
else
|
||||||
|
currentSearchResultGroup.AddReference(node);
|
||||||
|
}
|
||||||
|
else // List child GameObject scene objects under their parent GameObject
|
||||||
|
{
|
||||||
|
string dictionaryKey = searchedTopmostGameObject.GetEntityId().ToString();
|
||||||
|
List<ReferenceNode> unusedSubObjectNodesAtPath;
|
||||||
|
if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) )
|
||||||
|
unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
|
||||||
|
|
||||||
|
unusedSubObjectNodesAtPath.Add( node );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if( AssetDatabase.IsMainAsset( obj ) )
|
||||||
|
unusedMainObjectNodes[assetPath] = node;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
List<ReferenceNode> unusedSubObjectNodesAtPath;
|
||||||
|
if( !unusedSubObjectNodes.TryGetValue( assetPath, out unusedSubObjectNodesAtPath ) )
|
||||||
|
unusedSubObjectNodes[assetPath] = unusedSubObjectNodesAtPath = new List<ReferenceNode>( 2 );
|
||||||
|
|
||||||
|
unusedSubObjectNodesAtPath.Add( node );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach( KeyValuePair<string, ReferenceNode> kvPair in unusedMainObjectNodes )
|
||||||
|
{
|
||||||
|
List<ReferenceNode> unusedSubAssetNodesAtPath;
|
||||||
|
if( unusedSubObjectNodes.TryGetValue( kvPair.Key, out unusedSubAssetNodesAtPath ) )
|
||||||
|
{
|
||||||
|
currentSearchResultGroup.AddReference( kvPair.Value );
|
||||||
|
for( int i = 0; i < unusedSubAssetNodesAtPath.Count; i++ )
|
||||||
|
kvPair.Value.AddLinkTo( unusedSubAssetNodesAtPath[i] );
|
||||||
|
|
||||||
|
if( usedObjectPathsSet.Contains( kvPair.Key ) )
|
||||||
|
kvPair.Value.usedState = ReferenceNode.UsedState.MixedCollapsed;
|
||||||
|
|
||||||
|
unusedSubObjectNodes.Remove( kvPair.Key );
|
||||||
|
}
|
||||||
|
else if( !usedObjectPathsSet.Contains( kvPair.Key ) ) // If a main asset has sub-assets and all of them are used, consider the main asset as used, as well (especially useful for Sprite assets)
|
||||||
|
currentSearchResultGroup.AddReference( kvPair.Value );
|
||||||
|
else if( !AssetDatabase.Contains( (Object) kvPair.Value.nodeObject ) )
|
||||||
|
{
|
||||||
|
currentSearchResultGroup.AddReference( kvPair.Value );
|
||||||
|
kvPair.Value.usedState = ReferenceNode.UsedState.MixedCollapsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach( KeyValuePair<string, List<ReferenceNode>> kvPair in unusedSubObjectNodes ) // These aren't linked to any unusedMainObjectNodes, add them as root nodes to the search result group
|
||||||
|
{
|
||||||
|
foreach( ReferenceNode node in kvPair.Value )
|
||||||
|
currentSearchResultGroup.AddReference( node );
|
||||||
|
}
|
||||||
|
|
||||||
|
if( currentSearchResultGroup.NumberOfReferences > 0 )
|
||||||
|
{
|
||||||
|
for( int i = 0; i < currentSearchResultGroup.NumberOfReferences; i++ )
|
||||||
|
currentSearchResultGroup[i].InitializeRecursively();
|
||||||
|
|
||||||
|
searchResult.Insert( 0, currentSearchResultGroup );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -662,7 +804,6 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
objectsToSearchSet.Add( obj );
|
objectsToSearchSet.Add( obj );
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
// When searching for references of a prefab stage object, try adding its corresponding prefab asset to the searched assets, as well
|
// When searching for references of a prefab stage object, try adding its corresponding prefab asset to the searched assets, as well
|
||||||
if( openPrefabStage != null && openPrefabStagePrefabAsset != null && obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
|
if( openPrefabStage != null && openPrefabStagePrefabAsset != null && obj is GameObject && openPrefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
|
||||||
{
|
{
|
||||||
@@ -670,7 +811,6 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( prefabStageObjectSource != null )
|
if( prefabStageObjectSource != null )
|
||||||
AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects );
|
AddSearchedObjectToFilteredSets( prefabStageObjectSource, expandGameObjects );
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
bool isAsset = obj.IsAsset();
|
bool isAsset = obj.IsAsset();
|
||||||
if( isAsset )
|
if( isAsset )
|
||||||
@@ -681,7 +821,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( !string.IsNullOrEmpty( assetPath ) )
|
if( !string.IsNullOrEmpty( assetPath ) )
|
||||||
{
|
{
|
||||||
assetsToSearchPathsSet.Add( assetPath );
|
assetsToSearchPathsSet.Add( assetPath );
|
||||||
if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
|
if( searchParameters.dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
|
||||||
excludedAssetsPathsSet.Add( assetPath );
|
excludedAssetsPathsSet.Add( assetPath );
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -743,7 +883,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Search a scene for references
|
// Search a scene for references
|
||||||
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, bool lazySearch, SceneSetup[] initialSceneSetup )
|
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, Parameters searchParameters, SceneSetup[] initialSceneSetup )
|
||||||
{
|
{
|
||||||
Scene scene = EditorSceneManager.GetSceneByPath( scenePath );
|
Scene scene = EditorSceneManager.GetSceneByPath( scenePath );
|
||||||
if( isInPlayMode && !scene.isLoaded )
|
if( isInPlayMode && !scene.isLoaded )
|
||||||
@@ -759,7 +899,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
if( !scene.isLoaded )
|
if( !scene.isLoaded )
|
||||||
{
|
{
|
||||||
if( lazySearch )
|
if( searchParameters.lazySceneSearch )
|
||||||
{
|
{
|
||||||
searchResult.Add( new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene, true, true ) );
|
searchResult.Add( new SearchResultGroup( scenePath, SearchResultGroup.GroupType.Scene, true, true ) );
|
||||||
return;
|
return;
|
||||||
@@ -775,6 +915,16 @@ namespace AssetUsageDetectorNamespace
|
|||||||
for( int i = 0; i < rootGameObjects.Length; i++ )
|
for( int i = 0; i < rootGameObjects.Length; i++ )
|
||||||
SearchGameObjectRecursively( rootGameObjects[i] );
|
SearchGameObjectRecursively( rootGameObjects[i] );
|
||||||
|
|
||||||
|
// Search through Lighting Settings (it requires changing the active scene but don't do that in play mode)
|
||||||
|
if( searchParameters.searchInSceneLightingSettings && ( !isInPlayMode || SceneManager.GetActiveScene() == scene ) )
|
||||||
|
{
|
||||||
|
if( !isInPlayMode && EditorSceneManager.GetActiveScene() != scene )
|
||||||
|
EditorSceneManager.SetActiveScene( scene );
|
||||||
|
|
||||||
|
BeginSearchObject( lightmapSettingsGetter() );
|
||||||
|
BeginSearchObject( renderSettingsGetter() );
|
||||||
|
}
|
||||||
|
|
||||||
// If no references are found in the scene and if the scene is not part of the initial scene setup, close it
|
// If no references are found in the scene and if the scene is not part of the initial scene setup, close it
|
||||||
if( currentSearchResultGroup.NumberOfReferences == 0 )
|
if( currentSearchResultGroup.NumberOfReferences == 0 )
|
||||||
{
|
{
|
||||||
@@ -797,11 +947,9 @@ namespace AssetUsageDetectorNamespace
|
|||||||
EditorSceneManager.CloseScene( scene, true );
|
EditorSceneManager.CloseScene( scene, true );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
if( currentSearchResultGroup.AnyReferencesFound )
|
||||||
// Some references are found in this scene, save the results
|
|
||||||
searchResult.Add( currentSearchResultGroup );
|
searchResult.Add( currentSearchResultGroup );
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Search a GameObject and its children for references recursively
|
// Search a GameObject and its children for references recursively
|
||||||
@@ -833,27 +981,29 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( obj == null || obj.Equals( null ) )
|
if( obj == null || obj.Equals( null ) )
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
// Avoid recursion (which leads to stackoverflow exception) using a stack
|
// Avoid recursion (which leads to stackoverflow exception) using a stack (initially, I was using callStack.ContainsFast
|
||||||
if( callStack.ContainsFast( obj ) )
|
// here but it returned false for objects that do exist in the call stack if VFX Graph window was open)
|
||||||
return null;
|
for( int i = callStack.Count - 1; i >= 0; i-- )
|
||||||
|
{
|
||||||
|
if( callStack[i].Equals( obj ) )
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
|
bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj );
|
||||||
|
|
||||||
// Hashing does not work well with structs all the time, don't cache search results for structs
|
// Hashing does not work well with structs all the time, don't cache search results for structs
|
||||||
string objHash = null;
|
if( !( obj is ValueType ) && !searchingSourceAsset )
|
||||||
if( !( obj is ValueType ) )
|
|
||||||
{
|
{
|
||||||
objHash = obj.Hash();
|
// If object was searched before, return the cached result
|
||||||
|
ReferenceNode cachedResult;
|
||||||
if( !searchingSourceAsset )
|
if( TryGetReferenceNode( obj, out cachedResult ) )
|
||||||
{
|
return cachedResult;
|
||||||
// If object was searched before, return the cached result
|
|
||||||
ReferenceNode cachedResult;
|
|
||||||
if( searchedObjects.TryGetValue( objHash, out cachedResult ) )
|
|
||||||
return cachedResult;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Comply with the recursive search limit
|
||||||
|
if (callStack.Count >= searchParameters.searchDepthLimit)
|
||||||
|
return null;
|
||||||
|
|
||||||
searchedObjectsCount++;
|
searchedObjectsCount++;
|
||||||
|
|
||||||
ReferenceNode result;
|
ReferenceNode result;
|
||||||
@@ -866,14 +1016,14 @@ namespace AssetUsageDetectorNamespace
|
|||||||
{
|
{
|
||||||
if( assetsToSearchSet.Count == 0 )
|
if( assetsToSearchSet.Count == 0 )
|
||||||
{
|
{
|
||||||
searchedObjects.Add( objHash, null );
|
searchedUnityObjects.Add(unityObject.GetEntityId(), null);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
assetPath = AssetDatabase.GetAssetPath( unityObject );
|
assetPath = AssetDatabase.GetAssetPath( unityObject );
|
||||||
if( !AssetHasAnyReference( assetPath ) )
|
if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) )
|
||||||
{
|
{
|
||||||
searchedObjects.Add( objHash, null );
|
searchedUnityObjects.Add(unityObject.GetEntityId(), null);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -881,7 +1031,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
callStack.Add( unityObject );
|
callStack.Add( unityObject );
|
||||||
|
|
||||||
// Search the Object in detail
|
// Search the Object in detail
|
||||||
Func<Object, ReferenceNode> searchFunction;
|
Func<object, ReferenceNode> searchFunction;
|
||||||
if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) )
|
if( assetPath != null && extensionToSearchFunction.TryGetValue( Utilities.GetFileExtension( assetPath ), out searchFunction ) && AssetDatabase.IsMainAsset( unityObject ) )
|
||||||
result = searchFunction( unityObject );
|
result = searchFunction( unityObject );
|
||||||
else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) )
|
else if( typeToSearchFunction.TryGetValue( unityObject.GetType(), out searchFunction ) )
|
||||||
@@ -894,21 +1044,32 @@ namespace AssetUsageDetectorNamespace
|
|||||||
SearchVariablesWithSerializedObject( result );
|
SearchVariablesWithSerializedObject( result );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A prefab asset should have a link to its children because when a scene object uses a prefab and a child of that prefab uses
|
||||||
|
// a searched object, the scene object needs to appear in the search results. Since prefab assets aren't automatically linked to
|
||||||
|
// their children, we need to create that link manually
|
||||||
|
if( assetPath != null && unityObject is GameObject && AssetDatabase.IsMainAsset( unityObject ) )
|
||||||
|
{
|
||||||
|
if( result == null )
|
||||||
|
result = PopReferenceNode( unityObject );
|
||||||
|
|
||||||
|
GameObject prefabGameObject = (GameObject) unityObject;
|
||||||
|
Transform[] prefabChildren = prefabGameObject.GetComponentsInChildren<Transform>( true );
|
||||||
|
for( int i = 0; i < prefabChildren.Length; i++ )
|
||||||
|
{
|
||||||
|
if( prefabChildren[i].gameObject != prefabGameObject )
|
||||||
|
result.AddLinkTo( SearchObject( prefabChildren[i].gameObject ), isWeakLink: true );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
callStack.RemoveAt( callStack.Count - 1 );
|
callStack.RemoveAt( callStack.Count - 1 );
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Comply with the recursive search limit
|
|
||||||
if( currentDepth >= searchDepthLimit )
|
|
||||||
return null;
|
|
||||||
|
|
||||||
callStack.Add( obj );
|
callStack.Add( obj );
|
||||||
currentDepth++;
|
|
||||||
|
|
||||||
result = PopReferenceNode( obj );
|
result = PopReferenceNode( obj );
|
||||||
SearchVariablesWithReflection( result );
|
SearchVariablesWithReflection( result );
|
||||||
|
|
||||||
currentDepth--;
|
|
||||||
callStack.RemoveAt( callStack.Count - 1 );
|
callStack.RemoveAt( callStack.Count - 1 );
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -918,19 +1079,23 @@ namespace AssetUsageDetectorNamespace
|
|||||||
result = null;
|
result = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cache the search result if we are skimming through a class (not a struct; i.e. objHash != null)
|
// Cache the search result if we are skimming through a class (not a struct) and if the object is a UnityEngine.Object (if not,
|
||||||
// and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something
|
// cache the result only if we have actually found something or we are at the root of the search; i.e. callStack.Count == 0)
|
||||||
// or we are at the root of the search; i.e. currentDepth == 0)
|
if (obj is not ValueType && (result != null || unityObject != null || callStack.Count == 0))
|
||||||
if( objHash != null && ( result != null || unityObject != null || currentDepth == 0 ) )
|
{
|
||||||
{
|
if (!searchingSourceAsset)
|
||||||
if( !searchingSourceAsset )
|
{
|
||||||
searchedObjects.Add( objHash, result );
|
if (obj is Object)
|
||||||
else if( result != null )
|
searchedUnityObjects.Add(unityObject.GetEntityId(), result);
|
||||||
{
|
else
|
||||||
result.CopyReferencesTo( searchedObjects[objHash] );
|
searchedObjects.Add(GetNodeObjectHash(obj), result);
|
||||||
PoolReferenceNode( result );
|
}
|
||||||
}
|
else if (result != null)
|
||||||
}
|
{
|
||||||
|
result.CopyReferencesTo(searchedUnityObjects[unityObject.GetEntityId()]);
|
||||||
|
PoolReferenceNode(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -938,6 +1103,11 @@ namespace AssetUsageDetectorNamespace
|
|||||||
// Check if the asset at specified path depends on any of the references
|
// Check if the asset at specified path depends on any of the references
|
||||||
private bool AssetHasAnyReference( string assetPath )
|
private bool AssetHasAnyReference( string assetPath )
|
||||||
{
|
{
|
||||||
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
if( searchParameters.addressablesSupport )
|
||||||
|
return true;
|
||||||
|
#endif
|
||||||
|
|
||||||
if( assetsToSearchPathsSet.Contains( assetPath ) )
|
if( assetsToSearchPathsSet.Contains( assetPath ) )
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
@@ -979,7 +1149,10 @@ namespace AssetUsageDetectorNamespace
|
|||||||
// if that happens, log useful information to help reproduce the issue
|
// if that happens, log useful information to help reproduce the issue
|
||||||
if( lastRefreshedCacheEntry == cacheEntry )
|
if( lastRefreshedCacheEntry == cacheEntry )
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder( 1000 );
|
StringBuilder sb = Utilities.stringBuilder;
|
||||||
|
sb.Length = 0;
|
||||||
|
sb.EnsureCapacity( 1000 );
|
||||||
|
|
||||||
sb.AppendLine( "<b>Infinite loop while refreshing a cache entry, please report it to the author.</b>" ).AppendLine();
|
sb.AppendLine( "<b>Infinite loop while refreshing a cache entry, please report it to the author.</b>" ).AppendLine();
|
||||||
sb.Append( "Asset path: " ).AppendLine( assetPath );
|
sb.Append( "Asset path: " ).AppendLine( assetPath );
|
||||||
|
|
||||||
@@ -1048,19 +1221,46 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get reference node for object
|
// If object was already searched, return its ReferenceNode
|
||||||
private ReferenceNode GetReferenceNode( object nodeObject )
|
private bool TryGetReferenceNode(object nodeObject, out ReferenceNode referenceNode)
|
||||||
{
|
{
|
||||||
ReferenceNode result;
|
if (nodeObject is Object unityObject)
|
||||||
string hash = nodeObject.Hash();
|
{
|
||||||
if( !searchedObjects.TryGetValue( hash, out result ) || result == null )
|
if (searchedUnityObjects.TryGetValue(unityObject.GetEntityId(), out referenceNode))
|
||||||
{
|
return true;
|
||||||
result = PopReferenceNode( nodeObject );
|
}
|
||||||
searchedObjects[hash] = result;
|
else if (searchedObjects.TryGetValue(GetNodeObjectHash(nodeObject), out referenceNode))
|
||||||
}
|
return true;
|
||||||
|
|
||||||
return result;
|
referenceNode = null;
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get reference node for object
|
||||||
|
private ReferenceNode GetReferenceNode(object nodeObject)
|
||||||
|
{
|
||||||
|
ReferenceNode result;
|
||||||
|
if (nodeObject is Object unityObject)
|
||||||
|
{
|
||||||
|
EntityId hash = unityObject.GetEntityId();
|
||||||
|
if (!searchedUnityObjects.TryGetValue(hash, out result) || result == null)
|
||||||
|
{
|
||||||
|
result = PopReferenceNode(nodeObject);
|
||||||
|
searchedUnityObjects[hash] = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string hash = GetNodeObjectHash(nodeObject);
|
||||||
|
if (!searchedObjects.TryGetValue(hash, out result) || result == null)
|
||||||
|
{
|
||||||
|
result = PopReferenceNode(nodeObject);
|
||||||
|
searchedObjects[hash] = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
// Fetch a reference node from pool
|
// Fetch a reference node from pool
|
||||||
private ReferenceNode PopReferenceNode( object nodeObject )
|
private ReferenceNode PopReferenceNode( object nodeObject )
|
||||||
@@ -1086,6 +1286,12 @@ namespace AssetUsageDetectorNamespace
|
|||||||
nodesPool.Add( node );
|
nodesPool.Add( node );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get a unique-ish string hash code for a plain C# object (i.e. non-UnityEngine.Object object)
|
||||||
|
private string GetNodeObjectHash( object nodeObject )
|
||||||
|
{
|
||||||
|
return nodeObject.GetHashCode() + nodeObject.GetType().Name;
|
||||||
|
}
|
||||||
|
|
||||||
// Retrieve the game objects listed under the DontDestroyOnLoad scene
|
// Retrieve the game objects listed under the DontDestroyOnLoad scene
|
||||||
private GameObject[] GetDontDestroyOnLoadObjects()
|
private GameObject[] GetDontDestroyOnLoadObjects()
|
||||||
{
|
{
|
||||||
@@ -1106,5 +1312,48 @@ namespace AssetUsageDetectorNamespace
|
|||||||
Object.DestroyImmediate( temp );
|
Object.DestroyImmediate( temp );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Appends contents of callStack to StringBuilder and returns the most recent Unity object in callStack
|
||||||
|
private Object AppendCallStackToStringBuilder( StringBuilder sb )
|
||||||
|
{
|
||||||
|
Object latestUnityObjectInCallStack = null;
|
||||||
|
if( callStack.Count > 0 )
|
||||||
|
{
|
||||||
|
sb.AppendLine().AppendLine( "Stack contents: " );
|
||||||
|
|
||||||
|
for( int i = callStack.Count - 1; i >= 0; i-- )
|
||||||
|
{
|
||||||
|
latestUnityObjectInCallStack = callStack[i] as Object;
|
||||||
|
if( latestUnityObjectInCallStack )
|
||||||
|
{
|
||||||
|
if( !AssetDatabase.Contains( latestUnityObjectInCallStack ) )
|
||||||
|
{
|
||||||
|
string scenePath = AssetDatabase.GetAssetOrScenePath( latestUnityObjectInCallStack );
|
||||||
|
if( !string.IsNullOrEmpty( scenePath ) && SceneManager.GetSceneByPath( scenePath ).IsValid() )
|
||||||
|
sb.Append( "Scene: " ).AppendLine( scenePath );
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for( int i = callStack.Count - 1; i >= 0; i-- )
|
||||||
|
{
|
||||||
|
sb.Append( i ).Append( ": " );
|
||||||
|
|
||||||
|
Object unityObject = callStack[i] as Object;
|
||||||
|
if( unityObject )
|
||||||
|
sb.Append( unityObject.name ).Append( " (" ).Append( unityObject.GetType() ).AppendLine( ")" );
|
||||||
|
else if( callStack[i] != null )
|
||||||
|
sb.Append( callStack[i].GetType() ).AppendLine( " object" );
|
||||||
|
else
|
||||||
|
sb.AppendLine( "<<destroyed>>" );
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
|
return latestUnityObjectInCallStack;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,10 +51,35 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( fileSizes == null || fileSizes.Length != dependencies.Length )
|
if( fileSizes == null || fileSizes.Length != dependencies.Length )
|
||||||
fileSizes = new long[dependencies.Length];
|
fileSizes = new long[dependencies.Length];
|
||||||
|
|
||||||
for( int i = 0; i < dependencies.Length; i++ )
|
int length = dependencies.Length;
|
||||||
|
for( int i = 0; i < length; i++ )
|
||||||
{
|
{
|
||||||
FileInfo assetFile = new FileInfo( dependencies[i] );
|
if( !string.IsNullOrEmpty( dependencies[i] ) )
|
||||||
fileSizes[i] = assetFile.Exists ? assetFile.Length : 0L;
|
{
|
||||||
|
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 );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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:
|
||||||
@@ -1,50 +1,79 @@
|
|||||||
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
|
|
||||||
|
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
|
using UnityEditor.SceneManagement;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
|
|
||||||
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace AssetUsageDetectorNamespace
|
namespace AssetUsageDetectorNamespace
|
||||||
{
|
{
|
||||||
public enum Phase { Setup, Processing, Complete };
|
public enum Phase { Setup, Processing, Complete };
|
||||||
|
|
||||||
public class AssetUsageDetectorWindow : EditorWindow
|
public class AssetUsageDetectorWindow : EditorWindow, IHasCustomMenu
|
||||||
{
|
{
|
||||||
private const float PLAY_MODE_REFRESH_INTERVAL = 1f; // Interval to refresh the editor window in play mode
|
private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew };
|
||||||
|
|
||||||
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
|
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
|
||||||
|
private const string PREFS_SEARCH_SCENE_LIGHTING_SETTINGS = "AUD_LightingSettingsSearch";
|
||||||
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
|
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
|
||||||
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
|
private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
|
||||||
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
|
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
|
||||||
private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
|
private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
|
||||||
private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
|
|
||||||
private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties";
|
|
||||||
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
|
|
||||||
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
|
private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
|
||||||
private const string PREFS_PATH_DRAWING_MODE = "AUD_PathDrawing";
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
|
||||||
|
#endif
|
||||||
|
private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
|
||||||
|
private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
|
||||||
|
private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS = "AUD_HideRedundantPRefsInAssets";
|
||||||
|
private const string PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES = "AUD_HideRedundantPRefsInScenes";
|
||||||
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
|
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
|
||||||
private const string PREFS_SHOW_TOOLTIPS = "AUD_Tooltips";
|
|
||||||
|
|
||||||
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
|
private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
|
||||||
private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );
|
private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );
|
||||||
|
|
||||||
private AssetUsageDetector core = new AssetUsageDetector();
|
private static readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f );
|
||||||
|
|
||||||
|
private static readonly GUIContent sharedGUIContent = new GUIContent();
|
||||||
|
|
||||||
|
private readonly GUIContent hideRedundantPrefabReferencesInAssetsLabel = new GUIContent( "Hide redundant prefab references in Assets", "Hides redundant/non-overridden references in prefab variants and nested prefabs. " +
|
||||||
|
"This will help focus on only the references that actually matter. For example:\n\n" +
|
||||||
|
"- Material CloudMat is assigned to prefab Cloud and its variant CloudBig. Since changing Cloud's material will also affect CloudBig, search results won't show CloudBig's reference" );
|
||||||
|
private readonly GUIContent hideRedundantPrefabReferencesInScenesLabel = new GUIContent( "Hide redundant prefab references in Scenes", "Hides redundant/non-overridden references in prefab instances. " +
|
||||||
|
"This will help focus on only the references that actually matter. For example:\n\n" +
|
||||||
|
"- Prefab Healthbar is nested inside prefab Player. An instance of Player exists in the current scene and its Healthbar isn't modified. Since modifying Healthbar in Player prefab will also affect " +
|
||||||
|
"the instance in the scene, search results won't show the instance in the scene while searching for Healthbar's references" );
|
||||||
|
|
||||||
|
private GUIStyle lockButtonStyle;
|
||||||
|
|
||||||
|
private readonly AssetUsageDetector core = new AssetUsageDetector();
|
||||||
private SearchResult searchResult; // Overall search results
|
private SearchResult searchResult; // Overall search results
|
||||||
|
|
||||||
|
// This isn't readonly so that it can be serialized
|
||||||
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
|
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
|
||||||
|
|
||||||
|
[SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked
|
||||||
|
private bool m_isLocked;
|
||||||
|
private bool IsLocked
|
||||||
|
{
|
||||||
|
get { return m_isLocked; }
|
||||||
|
set
|
||||||
|
{
|
||||||
|
if( m_isLocked != value )
|
||||||
|
{
|
||||||
|
m_isLocked = value;
|
||||||
|
titleContent = value ? new GUIContent( "[L] " + windowTitle.text, EditorGUIUtility.IconContent( "InspectorLock" ).image ) : windowTitle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Phase currentPhase = Phase.Setup;
|
private Phase currentPhase = Phase.Setup;
|
||||||
|
|
||||||
private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view
|
private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view
|
||||||
private bool searchInScenesInBuild = true; // Scenes in build
|
private bool searchInScenesInBuild = true; // Scenes in build
|
||||||
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
|
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
|
||||||
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
|
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
|
||||||
|
private bool searchInSceneLightingSettings = true; // Window-Rendering-Lighting settings
|
||||||
private bool searchInAssetsFolder = true; // Assets in Project window
|
private bool searchInAssetsFolder = true; // Assets in Project window
|
||||||
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
|
private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
|
||||||
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
|
private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.
|
||||||
@@ -53,74 +82,116 @@ namespace AssetUsageDetectorNamespace
|
|||||||
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
|
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
|
||||||
private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references
|
private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references
|
||||||
|
|
||||||
private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects
|
private bool lazySceneSearch = true;
|
||||||
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
private bool restoreInitialSceneSetup = true; // Close the additively loaded scenes that were not part of the initial scene setup
|
private bool addressablesSupport = false;
|
||||||
|
#endif
|
||||||
private string errorMessage = string.Empty;
|
private bool searchUnusedMaterialProperties = true;
|
||||||
|
private bool calculateUnusedObjects = false;
|
||||||
private bool lazySceneSearch = false;
|
private bool hideDuplicateRows = true;
|
||||||
private bool searchNonSerializableVariables = true;
|
private bool hideRedundantPrefabReferencesInAssets = false;
|
||||||
|
private bool hideRedundantPrefabReferencesInScenes = false;
|
||||||
private bool noAssetDatabaseChanges = false;
|
private bool noAssetDatabaseChanges = false;
|
||||||
private bool showDetailedProgressBar = false;
|
private bool showDetailedProgressBar = true;
|
||||||
|
|
||||||
private BindingFlags fieldModifiers, propertyModifiers;
|
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
|
||||||
|
|
||||||
private SearchResultDrawParameters searchResultDrawParameters = new SearchResultDrawParameters( PathDrawingMode.ShortRelevantParts, false, false );
|
|
||||||
|
|
||||||
private double nextPlayModeRefreshTime = 0f;
|
|
||||||
|
|
||||||
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
|
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
|
||||||
private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
|
private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
|
||||||
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
|
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
|
||||||
private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );
|
private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );
|
||||||
|
|
||||||
private readonly GUIContent restoreInitialSceneSetupLabel = new GUIContent( "Restore initial scene setup (Recommended)", "For example, if scene A was open when the search was started and scenes A and B are open after the search is completed, clicking the \"Reset Search\" button will automatically close scene B" );
|
private bool drawObjectsToSearchSection = true;
|
||||||
private readonly GUIContent showTooltipsLabel = new GUIContent( "Show tooltips", "Display nodes' contents in a tooltip when cursor hovers over them" );
|
|
||||||
|
|
||||||
private Vector2 scrollPosition = Vector2.zero;
|
private Vector2 scrollPosition = Vector2.zero;
|
||||||
|
|
||||||
private bool shouldRepositionSelf;
|
private bool shouldRepositionSelf;
|
||||||
private Rect windowTargetPosition;
|
private Rect windowTargetPosition;
|
||||||
|
|
||||||
private static AssetUsageDetectorWindow mainWindow = null;
|
void IHasCustomMenu.AddItemsToMenu( GenericMenu contextMenu )
|
||||||
|
{
|
||||||
|
contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked );
|
||||||
|
contextMenu.AddSeparator( "" );
|
||||||
|
contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) );
|
||||||
|
|
||||||
|
if( currentPhase == Phase.Setup )
|
||||||
|
{
|
||||||
|
contextMenu.AddSeparator( "" );
|
||||||
|
contextMenu.AddItem( new GUIContent( "Refresh Sub-Assets of Searched Objects" ), false, () =>
|
||||||
|
{
|
||||||
|
for( int i = objectsToSearch.Count - 1; i >= 0; i-- )
|
||||||
|
objectsToSearch[i].RefreshSubAssets();
|
||||||
|
} );
|
||||||
|
}
|
||||||
|
else if( currentPhase == Phase.Complete )
|
||||||
|
{
|
||||||
|
if( searchResult != null && searchResult.NumberOfGroups > 0 )
|
||||||
|
{
|
||||||
|
contextMenu.AddSeparator( "" );
|
||||||
|
contextMenu.AddItem( new GUIContent( "Collapse All" ), false, searchResult.CollapseAllSearchResultGroups );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shows lock button at the top-right corner
|
||||||
|
// Credit: http://leahayes.co.uk/2013/04/30/adding-the-little-padlock-button-to-your-editorwindow.html
|
||||||
|
private void ShowButton( Rect position )
|
||||||
|
{
|
||||||
|
if( lockButtonStyle == null )
|
||||||
|
lockButtonStyle = "IN LockButton";
|
||||||
|
|
||||||
|
IsLocked = GUI.Toggle( position, IsLocked, GUIContent.none, lockButtonStyle );
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AssetUsageDetectorWindow GetWindow( WindowFilter filter )
|
||||||
|
{
|
||||||
|
AssetUsageDetectorWindow[] windows = Resources.FindObjectsOfTypeAll<AssetUsageDetectorWindow>();
|
||||||
|
AssetUsageDetectorWindow window = System.Array.Find( windows, ( w ) => w && !w.IsLocked );
|
||||||
|
if( !window )
|
||||||
|
window = System.Array.Find( windows, ( w ) => w );
|
||||||
|
|
||||||
|
if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
|
||||||
|
{
|
||||||
|
window.Show();
|
||||||
|
window.Focus();
|
||||||
|
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
|
||||||
|
Rect? windowTargetPosition = null;
|
||||||
|
if( window )
|
||||||
|
{
|
||||||
|
Rect position = window.position;
|
||||||
|
position.position += new Vector2( 50f, 50f );
|
||||||
|
windowTargetPosition = position;
|
||||||
|
}
|
||||||
|
|
||||||
|
window = CreateInstance<AssetUsageDetectorWindow>();
|
||||||
|
window.titleContent = windowTitle;
|
||||||
|
window.minSize = windowMinSize;
|
||||||
|
|
||||||
|
if( windowTargetPosition.HasValue )
|
||||||
|
{
|
||||||
|
window.shouldRepositionSelf = true;
|
||||||
|
window.windowTargetPosition = windowTargetPosition.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.Show( true );
|
||||||
|
window.Focus();
|
||||||
|
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
|
||||||
// Add "Asset Usage Detector" menu item to the Window menu
|
|
||||||
[MenuItem( "Window/Asset Usage Detector/Active Window" )]
|
[MenuItem( "Window/Asset Usage Detector/Active Window" )]
|
||||||
private static void OpenActiveWindow()
|
private static void OpenActiveWindow()
|
||||||
{
|
{
|
||||||
if( !mainWindow )
|
GetWindow( WindowFilter.AlwaysReturnActive );
|
||||||
{
|
|
||||||
mainWindow = GetWindow<AssetUsageDetectorWindow>();
|
|
||||||
mainWindow.titleContent = windowTitle;
|
|
||||||
mainWindow.minSize = windowMinSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
mainWindow.Show();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[MenuItem( "Window/Asset Usage Detector/New Window" )]
|
[MenuItem( "Window/Asset Usage Detector/New Window" )]
|
||||||
private static void OpenNewWindow()
|
private static void OpenNewWindow()
|
||||||
{
|
{
|
||||||
Rect? windowTargetPosition = null;
|
GetWindow( WindowFilter.AlwaysReturnNew );
|
||||||
if( mainWindow )
|
|
||||||
{
|
|
||||||
Rect position = mainWindow.position;
|
|
||||||
position.position += new Vector2( 50f, 50f );
|
|
||||||
windowTargetPosition = position;
|
|
||||||
}
|
|
||||||
|
|
||||||
mainWindow = CreateInstance<AssetUsageDetectorWindow>();
|
|
||||||
mainWindow.titleContent = windowTitle;
|
|
||||||
mainWindow.minSize = windowMinSize;
|
|
||||||
|
|
||||||
if( windowTargetPosition.HasValue )
|
|
||||||
{
|
|
||||||
mainWindow.shouldRepositionSelf = true;
|
|
||||||
mainWindow.windowTargetPosition = windowTargetPosition.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
mainWindow.Show( true );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Quickly initiate search for the selected assets
|
// Quickly initiate search for the selected assets
|
||||||
@@ -164,7 +235,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
// Quickly show the AssetUsageDetector window and initiate a search
|
// Quickly show the AssetUsageDetector window and initiate a search
|
||||||
public static void ShowAndSearch( IEnumerable<Object> searchObjects, bool? shouldSearchChildren = null )
|
public static void ShowAndSearch( IEnumerable<Object> searchObjects, bool? shouldSearchChildren = null )
|
||||||
{
|
{
|
||||||
ShowAndSearchInternal( searchObjects, null, shouldSearchChildren );
|
GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchObjects, null, shouldSearchChildren );
|
||||||
}
|
}
|
||||||
|
|
||||||
// Quickly show the AssetUsageDetector window and initiate a search
|
// Quickly show the AssetUsageDetector window and initiate a search
|
||||||
@@ -176,7 +247,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren );
|
GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren );
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CallSearchSelectedAssetReferencesOnce()
|
private static void CallSearchSelectedAssetReferencesOnce()
|
||||||
@@ -191,61 +262,65 @@ namespace AssetUsageDetectorNamespace
|
|||||||
SearchSelectedAssetReferencesWithChildren( new MenuCommand( null ) );
|
SearchSelectedAssetReferencesWithChildren( new MenuCommand( null ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren )
|
private void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren )
|
||||||
{
|
{
|
||||||
if( mainWindow != null && !mainWindow.ReturnToSetupPhase( true, true ) )
|
if( !ReturnToSetupPhase() )
|
||||||
{
|
{
|
||||||
Debug.LogError( "Need to reset the previous search first!" );
|
Debug.LogError( "Need to reset the previous search first!" );
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
OpenActiveWindow();
|
objectsToSearch.Clear();
|
||||||
|
|
||||||
mainWindow.objectsToSearch.Clear();
|
|
||||||
if( searchObjects != null )
|
if( searchObjects != null )
|
||||||
{
|
{
|
||||||
foreach( Object obj in searchObjects )
|
foreach( Object obj in searchObjects )
|
||||||
mainWindow.objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) );
|
objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
if( searchParameters != null )
|
if( searchParameters != null )
|
||||||
{
|
{
|
||||||
mainWindow.ParseSceneSearchMode( searchParameters.searchInScenes );
|
ParseSceneSearchMode( searchParameters.searchInScenes );
|
||||||
mainWindow.searchInAssetsFolder = searchParameters.searchInAssetsFolder;
|
searchInSceneLightingSettings = searchParameters.searchInSceneLightingSettings;
|
||||||
mainWindow.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
|
searchInAssetsFolder = searchParameters.searchInAssetsFolder;
|
||||||
mainWindow.searchInProjectSettings = searchParameters.searchInProjectSettings;
|
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
|
||||||
mainWindow.searchDepthLimit = searchParameters.searchDepthLimit;
|
searchInProjectSettings = searchParameters.searchInProjectSettings;
|
||||||
mainWindow.fieldModifiers = searchParameters.fieldModifiers;
|
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
|
||||||
mainWindow.propertyModifiers = searchParameters.propertyModifiers;
|
searchRefactoring = searchParameters.searchRefactoring;
|
||||||
mainWindow.searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
|
lazySceneSearch = searchParameters.lazySceneSearch;
|
||||||
mainWindow.lazySceneSearch = searchParameters.lazySceneSearch;
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
mainWindow.noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
|
addressablesSupport = searchParameters.addressablesSupport;
|
||||||
mainWindow.showDetailedProgressBar = searchParameters.showDetailedProgressBar;
|
#endif
|
||||||
|
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
|
||||||
|
hideDuplicateRows = searchParameters.hideDuplicateRows;
|
||||||
|
hideRedundantPrefabReferencesInAssets = searchParameters.hideRedundantPrefabReferencesInAssets;
|
||||||
|
hideRedundantPrefabReferencesInScenes = searchParameters.hideRedundantPrefabReferencesInScenes;
|
||||||
|
noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
|
||||||
|
showDetailedProgressBar = searchParameters.showDetailedProgressBar;
|
||||||
|
|
||||||
mainWindow.searchInAssetsSubset.Clear();
|
searchInAssetsSubset.Clear();
|
||||||
if( searchParameters.searchInAssetsSubset != null )
|
if( searchParameters.searchInAssetsSubset != null )
|
||||||
{
|
{
|
||||||
foreach( Object obj in searchParameters.searchInAssetsSubset )
|
foreach( Object obj in searchParameters.searchInAssetsSubset )
|
||||||
mainWindow.searchInAssetsSubset.Add( obj );
|
searchInAssetsSubset.Add( obj );
|
||||||
}
|
}
|
||||||
|
|
||||||
mainWindow.excludedAssets.Clear();
|
excludedAssets.Clear();
|
||||||
if( searchParameters.excludedAssetsFromSearch != null )
|
if( searchParameters.excludedAssetsFromSearch != null )
|
||||||
{
|
{
|
||||||
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
|
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
|
||||||
mainWindow.excludedAssets.Add( obj );
|
excludedAssets.Add( obj );
|
||||||
}
|
}
|
||||||
|
|
||||||
mainWindow.excludedScenes.Clear();
|
excludedScenes.Clear();
|
||||||
if( searchParameters.excludedScenesFromSearch != null )
|
if( searchParameters.excludedScenesFromSearch != null )
|
||||||
{
|
{
|
||||||
foreach( Object obj in searchParameters.excludedScenesFromSearch )
|
foreach( Object obj in searchParameters.excludedScenesFromSearch )
|
||||||
mainWindow.excludedScenes.Add( obj );
|
excludedScenes.Add( obj );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mainWindow.InitiateSearch();
|
InitiateSearch();
|
||||||
mainWindow.Repaint();
|
Repaint();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Awake()
|
private void Awake()
|
||||||
@@ -255,22 +330,16 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
private void OnEnable()
|
private void OnEnable()
|
||||||
{
|
{
|
||||||
mainWindow = this;
|
if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip )
|
||||||
|
wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
|
|
||||||
PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
|
PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDisable()
|
private void OnDisable()
|
||||||
{
|
{
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
|
PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
|
||||||
#endif
|
SearchResultTooltip.Hide();
|
||||||
|
|
||||||
if( mainWindow == this )
|
|
||||||
mainWindow = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDestroy()
|
private void OnDestroy()
|
||||||
@@ -281,56 +350,45 @@ namespace AssetUsageDetectorNamespace
|
|||||||
SavePrefs();
|
SavePrefs();
|
||||||
|
|
||||||
if( searchResult != null && currentPhase == Phase.Complete )
|
if( searchResult != null && currentPhase == Phase.Complete )
|
||||||
searchResult.RestoreInitialSceneSetup( true );
|
searchResult.RestoreInitialSceneSetup();
|
||||||
}
|
|
||||||
|
|
||||||
private void OnFocus()
|
|
||||||
{
|
|
||||||
mainWindow = this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SavePrefs()
|
private void SavePrefs()
|
||||||
{
|
{
|
||||||
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
|
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
|
||||||
|
EditorPrefs.SetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, searchInSceneLightingSettings );
|
||||||
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
|
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
|
||||||
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
|
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
|
||||||
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
|
EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
|
||||||
EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
|
EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
|
||||||
EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers );
|
|
||||||
EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers );
|
|
||||||
EditorPrefs.SetInt( PREFS_PATH_DRAWING_MODE, (int) searchResultDrawParameters.pathDrawingMode );
|
|
||||||
EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
|
|
||||||
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
|
EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
|
||||||
EditorPrefs.SetBool( PREFS_SHOW_TOOLTIPS, searchResultDrawParameters.showTooltips );
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
EditorPrefs.SetBool( PREFS_ADDRESSABLES_SUPPORT, addressablesSupport );
|
||||||
|
#endif
|
||||||
|
EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
|
||||||
|
EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
|
||||||
|
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
|
||||||
|
EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
|
||||||
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
|
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LoadPrefs()
|
private void LoadPrefs()
|
||||||
{
|
{
|
||||||
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
|
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
|
||||||
|
searchInSceneLightingSettings = EditorPrefs.GetBool( PREFS_SEARCH_SCENE_LIGHTING_SETTINGS, true );
|
||||||
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
|
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
|
||||||
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
|
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
|
||||||
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
|
searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
|
||||||
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
|
searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
|
||||||
|
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
|
||||||
// Fetch public, protected and private non-static fields and properties from objects by default
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
fieldModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_FIELDS, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
|
addressablesSupport = EditorPrefs.GetBool( PREFS_ADDRESSABLES_SUPPORT, false );
|
||||||
propertyModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_PROPERTIES, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
|
#endif
|
||||||
|
calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
|
||||||
try
|
hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
|
||||||
{
|
hideRedundantPrefabReferencesInAssets = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_ASSETS, hideRedundantPrefabReferencesInAssets );
|
||||||
searchResultDrawParameters.pathDrawingMode = (PathDrawingMode) EditorPrefs.GetInt( PREFS_PATH_DRAWING_MODE, (int) PathDrawingMode.ShortRelevantParts );
|
hideRedundantPrefabReferencesInScenes = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_REFERENCES_IN_SCENES, hideRedundantPrefabReferencesInScenes );
|
||||||
}
|
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
|
||||||
catch
|
|
||||||
{
|
|
||||||
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
|
|
||||||
}
|
|
||||||
|
|
||||||
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
|
|
||||||
lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, false );
|
|
||||||
searchResultDrawParameters.showTooltips = EditorPrefs.GetBool( PREFS_SHOW_TOOLTIPS, false );
|
|
||||||
showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, false );
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
|
private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
|
||||||
@@ -359,13 +417,6 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
private void Update()
|
private void Update()
|
||||||
{
|
{
|
||||||
// Refresh the window at a regular interval in play mode to update the tooltip
|
|
||||||
if( EditorApplication.isPlaying && currentPhase == Phase.Complete && searchResultDrawParameters.showTooltips && EditorApplication.timeSinceStartup >= nextPlayModeRefreshTime )
|
|
||||||
{
|
|
||||||
nextPlayModeRefreshTime = EditorApplication.timeSinceStartup + PLAY_MODE_REFRESH_INTERVAL; ;
|
|
||||||
Repaint();
|
|
||||||
}
|
|
||||||
|
|
||||||
if( shouldRepositionSelf )
|
if( shouldRepositionSelf )
|
||||||
{
|
{
|
||||||
shouldRepositionSelf = false;
|
shouldRepositionSelf = false;
|
||||||
@@ -380,160 +431,96 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
GUILayout.BeginVertical();
|
GUILayout.BeginVertical();
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
// Show the error message, if it is not empty
|
|
||||||
if( errorMessage.Length > 0 )
|
|
||||||
EditorGUILayout.HelpBox( errorMessage, MessageType.Error );
|
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
if( currentPhase == Phase.Processing )
|
if( currentPhase == Phase.Processing )
|
||||||
{
|
{
|
||||||
// If we are stuck at this phase, then we have encountered an exception
|
// If we are stuck at this phase, then we have encountered an exception
|
||||||
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
|
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
|
||||||
|
|
||||||
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
|
|
||||||
|
|
||||||
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
|
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
|
||||||
ReturnToSetupPhase( restoreInitialSceneSetup, false );
|
{
|
||||||
|
ReturnToSetupPhase();
|
||||||
|
GUIUtility.ExitGUI();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if( currentPhase == Phase.Setup )
|
else if( currentPhase == Phase.Setup )
|
||||||
{
|
{
|
||||||
if( objectsToSearchDrawer.Draw( objectsToSearch ) )
|
DrawObjectsToSearchSection();
|
||||||
errorMessage = string.Empty;
|
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
GUILayout.Space( 10f );
|
||||||
|
|
||||||
Color c = GUI.color;
|
Utilities.DrawHeader( "<b>SEARCH IN</b>" );
|
||||||
GUI.color = Color.cyan;
|
|
||||||
|
|
||||||
GUILayout.Box( "SEARCH IN", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
|
||||||
|
|
||||||
GUI.color = c;
|
|
||||||
|
|
||||||
searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );
|
|
||||||
|
|
||||||
if( searchInAssetsFolder )
|
if( searchInAssetsFolder )
|
||||||
{
|
{
|
||||||
GUILayout.BeginHorizontal();
|
BeginIndentedGUI();
|
||||||
GUILayout.Space( 35 );
|
|
||||||
GUILayout.BeginVertical();
|
|
||||||
|
|
||||||
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
|
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
|
||||||
excludedAssetsDrawer.Draw( excludedAssets );
|
excludedAssetsDrawer.Draw( excludedAssets );
|
||||||
|
EndIndentedGUI();
|
||||||
dontSearchInSourceAssets = EditorGUILayout.ToggleLeft( "Don't search \"Find references of\" themselves for references", dontSearchInSourceAssets );
|
|
||||||
|
|
||||||
GUILayout.EndVertical();
|
|
||||||
GUILayout.EndHorizontal();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
GUILayout.Space( 5f );
|
||||||
|
|
||||||
|
dontSearchInSourceAssets = WordWrappingToggleLeft( "Don't search \"SEARCHED OBJECTS\" themselves for references", dontSearchInSourceAssets );
|
||||||
|
searchUnusedMaterialProperties = WordWrappingToggleLeft( "Search unused material properties (e.g. normal map of a material that no longer uses normal mapping)", searchUnusedMaterialProperties );
|
||||||
|
|
||||||
Utilities.DrawSeparatorLine();
|
Utilities.DrawSeparatorLine();
|
||||||
|
|
||||||
if( searchInAllScenes && !EditorApplication.isPlaying )
|
if( searchInAllScenes && !EditorApplication.isPlaying )
|
||||||
GUI.enabled = false;
|
GUI.enabled = false;
|
||||||
|
|
||||||
searchInOpenScenes = EditorGUILayout.ToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes );
|
searchInOpenScenes = WordWrappingToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes );
|
||||||
|
|
||||||
if( !EditorApplication.isPlaying )
|
if( !EditorApplication.isPlaying )
|
||||||
{
|
{
|
||||||
searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", searchInScenesInBuild );
|
searchInScenesInBuild = WordWrappingToggleLeft( "Scenes in Build Settings", searchInScenesInBuild );
|
||||||
|
|
||||||
if( searchInScenesInBuild )
|
if( searchInScenesInBuild )
|
||||||
{
|
{
|
||||||
GUILayout.BeginHorizontal();
|
BeginIndentedGUI( false );
|
||||||
GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
|
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
|
||||||
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
|
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
|
||||||
|
EndIndentedGUI( false );
|
||||||
GUILayout.EndHorizontal();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
GUI.enabled = true;
|
GUI.enabled = true;
|
||||||
|
|
||||||
searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes );
|
searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes );
|
||||||
}
|
}
|
||||||
|
|
||||||
GUILayout.BeginHorizontal();
|
BeginIndentedGUI();
|
||||||
GUILayout.Space( 35 );
|
|
||||||
GUILayout.BeginVertical();
|
|
||||||
|
|
||||||
excludedScenesDrawer.Draw( excludedScenes );
|
excludedScenesDrawer.Draw( excludedScenes );
|
||||||
|
EndIndentedGUI();
|
||||||
|
|
||||||
GUILayout.EndVertical();
|
EditorGUI.BeginDisabledGroup( !searchInOpenScenes && !searchInScenesInBuild && !searchInAllScenes );
|
||||||
GUILayout.EndHorizontal();
|
searchInSceneLightingSettings = WordWrappingToggleLeft( "Scene Lighting Settings (WARNING: This may change the active scene during search)", searchInSceneLightingSettings );
|
||||||
|
EditorGUI.EndDisabledGroup();
|
||||||
|
|
||||||
Utilities.DrawSeparatorLine();
|
Utilities.DrawSeparatorLine();
|
||||||
|
|
||||||
searchInProjectSettings = EditorGUILayout.ToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );
|
searchInProjectSettings = WordWrappingToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
GUILayout.Space( 10f );
|
||||||
|
|
||||||
//GUILayout.Box( "SEARCH SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
Utilities.DrawHeader( "<b>SETTINGS</b>" );
|
||||||
|
|
||||||
//GUILayout.BeginHorizontal();
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
EditorGUI.BeginDisabledGroup( addressablesSupport );
|
||||||
|
#endif
|
||||||
|
lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
|
||||||
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
EditorGUI.EndDisabledGroup();
|
||||||
|
addressablesSupport = WordWrappingToggleLeft( "Addressables support (Experimental) (WARNING: 'Lazy scene search' will be disabled) (slower search)", addressablesSupport );
|
||||||
|
#endif
|
||||||
|
calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
|
||||||
|
hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
|
||||||
|
hideRedundantPrefabReferencesInAssets = WordWrappingToggleLeft( hideRedundantPrefabReferencesInAssetsLabel, hideRedundantPrefabReferencesInAssets );
|
||||||
|
hideRedundantPrefabReferencesInScenes = WordWrappingToggleLeft( hideRedundantPrefabReferencesInScenesLabel, hideRedundantPrefabReferencesInScenes );
|
||||||
|
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
|
||||||
|
showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar );
|
||||||
|
|
||||||
//GUILayout.Label( new GUIContent( "> Search depth: " + searchDepthLimit, "Depth limit for recursively searching variables of objects" ), Utilities.GL_WIDTH_250 );
|
GUILayout.Space( 10f );
|
||||||
|
|
||||||
//searchDepthLimit = (int) GUILayout.HorizontalSlider( searchDepthLimit, 0, 4 );
|
|
||||||
|
|
||||||
//GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Label( "> Search variables:" );
|
|
||||||
|
|
||||||
//GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
//if( EditorGUILayout.ToggleLeft( "Public", ( fieldModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) )
|
|
||||||
// fieldModifiers |= BindingFlags.Public;
|
|
||||||
//else
|
|
||||||
// fieldModifiers &= ~BindingFlags.Public;
|
|
||||||
|
|
||||||
//if( EditorGUILayout.ToggleLeft( "Non-public", ( fieldModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) )
|
|
||||||
// fieldModifiers |= BindingFlags.NonPublic;
|
|
||||||
//else
|
|
||||||
// fieldModifiers &= ~BindingFlags.NonPublic;
|
|
||||||
|
|
||||||
//GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Label( "> Search properties:" );
|
|
||||||
|
|
||||||
//GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
//if( EditorGUILayout.ToggleLeft( "Public", ( propertyModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) )
|
|
||||||
// propertyModifiers |= BindingFlags.Public;
|
|
||||||
//else
|
|
||||||
// propertyModifiers &= ~BindingFlags.Public;
|
|
||||||
|
|
||||||
//if( EditorGUILayout.ToggleLeft( "Non-public", ( propertyModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) )
|
|
||||||
// propertyModifiers |= BindingFlags.NonPublic;
|
|
||||||
//else
|
|
||||||
// propertyModifiers &= ~BindingFlags.NonPublic;
|
|
||||||
|
|
||||||
//GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
//searchNonSerializableVariables = EditorGUILayout.ToggleLeft( "Search non-serializable fields and properties", searchNonSerializableVariables );
|
|
||||||
|
|
||||||
//GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
GUI.color = Color.cyan;
|
|
||||||
|
|
||||||
GUILayout.Box( "SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
|
||||||
|
|
||||||
GUI.color = c;
|
|
||||||
|
|
||||||
lazySceneSearch = EditorGUILayout.ToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
|
|
||||||
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
|
|
||||||
showDetailedProgressBar = EditorGUILayout.ToggleLeft( "Show detailed progress bar (slower search)", showDetailedProgressBar );
|
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
// Don't let the user press the GO button without any valid search location
|
// Don't let the user press the GO button without any valid search location
|
||||||
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings )
|
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings )
|
||||||
@@ -544,21 +531,26 @@ namespace AssetUsageDetectorNamespace
|
|||||||
InitiateSearch();
|
InitiateSearch();
|
||||||
GUIUtility.ExitGUI();
|
GUIUtility.ExitGUI();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
GUILayout.Space( 5f );
|
||||||
}
|
}
|
||||||
else if( currentPhase == Phase.Complete )
|
else if( currentPhase == Phase.Complete )
|
||||||
{
|
{
|
||||||
// Draw the results of the search
|
// Draw the results of the search
|
||||||
GUI.enabled = false;
|
GUI.enabled = false;
|
||||||
|
|
||||||
objectsToSearchDrawer.Draw( objectsToSearch );
|
DrawObjectsToSearchSection();
|
||||||
|
|
||||||
|
if( drawObjectsToSearchSection )
|
||||||
|
GUILayout.Space( 10f );
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
|
||||||
GUI.enabled = true;
|
GUI.enabled = true;
|
||||||
|
|
||||||
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( restoreInitialSceneSetupLabel, restoreInitialSceneSetup );
|
|
||||||
|
|
||||||
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
|
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
|
||||||
ReturnToSetupPhase( restoreInitialSceneSetup, false );
|
{
|
||||||
|
ReturnToSetupPhase();
|
||||||
|
GUIUtility.ExitGUI();
|
||||||
|
}
|
||||||
|
|
||||||
if( searchResult == null )
|
if( searchResult == null )
|
||||||
{
|
{
|
||||||
@@ -568,143 +560,138 @@ namespace AssetUsageDetectorNamespace
|
|||||||
else if( !searchResult.SearchCompletedSuccessfully )
|
else if( !searchResult.SearchCompletedSuccessfully )
|
||||||
EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error );
|
EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error );
|
||||||
|
|
||||||
Color c = GUI.color;
|
|
||||||
GUI.color = Color.green;
|
|
||||||
GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
|
||||||
GUI.color = c;
|
|
||||||
|
|
||||||
if( searchResult.NumberOfGroups == 0 )
|
if( searchResult.NumberOfGroups == 0 )
|
||||||
{
|
{
|
||||||
GUILayout.Space( 10 );
|
GUILayout.Space( 10f );
|
||||||
GUILayout.Box( "No references found...", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
GUILayout.Box( "No references found...", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
//GUILayout.Space( 10 );
|
noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges );
|
||||||
//GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
//// Select all the references after filtering them (select only the GameObject's)
|
EditorGUILayout.Space();
|
||||||
//if( GUILayout.Button( "Select All\n(GameObject-wise)", Utilities.GL_HEIGHT_35 ) )
|
|
||||||
//{
|
|
||||||
// GameObject[] objects = searchResult.SelectAllAsGameObjects();
|
|
||||||
// if( objects != null && objects.Length > 0 )
|
|
||||||
// Selection.objects = objects;
|
|
||||||
//}
|
|
||||||
|
|
||||||
//// Select all the references without filtering them
|
scrollPosition.y = searchResult.DrawOnGUI( this, scrollPosition.y, noAssetDatabaseChanges );
|
||||||
//if( GUILayout.Button( "Select All\n(Object-wise)", Utilities.GL_HEIGHT_35 ) )
|
|
||||||
//{
|
|
||||||
// Object[] objects = searchResult.SelectAllAsObjects();
|
|
||||||
// if( objects != null && objects.Length > 0 )
|
|
||||||
// Selection.objects = objects;
|
|
||||||
//}
|
|
||||||
|
|
||||||
//GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
//GUILayout.Space( 10 );
|
|
||||||
|
|
||||||
searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( showTooltipsLabel, searchResultDrawParameters.showTooltips );
|
|
||||||
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges );
|
|
||||||
searchResultDrawParameters.noAssetDatabaseChanges = noAssetDatabaseChanges;
|
|
||||||
|
|
||||||
Utilities.DrawSeparatorLine();
|
|
||||||
|
|
||||||
GUILayout.Label( "Path drawing mode:" );
|
|
||||||
|
|
||||||
GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
|
|
||||||
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full;
|
|
||||||
|
|
||||||
GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant parts (that start with a UnityEngine.Object) of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
|
|
||||||
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
|
|
||||||
|
|
||||||
GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
GUILayout.BeginHorizontal();
|
|
||||||
|
|
||||||
GUILayout.Space( 35 );
|
|
||||||
|
|
||||||
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
|
|
||||||
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest;
|
|
||||||
|
|
||||||
GUILayout.EndHorizontal();
|
|
||||||
|
|
||||||
searchResult.DrawOnGUI( searchResultDrawParameters );
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GUILayout.Space( 10 );
|
if( Event.current.type == EventType.MouseLeaveWindow )
|
||||||
|
{
|
||||||
|
SearchResultTooltip.Hide();
|
||||||
|
|
||||||
|
if( searchResult != null )
|
||||||
|
searchResult.CancelDelayedTreeViewTooltip();
|
||||||
|
}
|
||||||
|
|
||||||
GUILayout.EndVertical();
|
GUILayout.EndVertical();
|
||||||
|
|
||||||
EditorGUILayout.EndScrollView();
|
EditorGUILayout.EndScrollView();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void InitiateSearch()
|
private void DrawObjectsToSearchSection()
|
||||||
{
|
{
|
||||||
if( objectsToSearch.IsEmpty() )
|
Utilities.DrawHeader( "<b>SEARCHED OBJECTS</b>" );
|
||||||
errorMessage = "ADD AN ASSET TO THE LIST FIRST!";
|
|
||||||
else if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
|
|
||||||
{
|
|
||||||
// Don't start the search if at least one scene is currently dirty (not saved)
|
|
||||||
errorMessage = "SAVE OPEN SCENES FIRST!";
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
errorMessage = string.Empty;
|
|
||||||
currentPhase = Phase.Processing;
|
|
||||||
|
|
||||||
SavePrefs();
|
Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect();
|
||||||
|
searchedObjectsHeaderRect.x += 5f;
|
||||||
|
searchedObjectsHeaderRect.yMin += ( searchedObjectsHeaderRect.height - EditorGUIUtility.singleLineHeight ) * 0.5f;
|
||||||
|
searchedObjectsHeaderRect.height = EditorGUIUtility.singleLineHeight;
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
drawObjectsToSearchSection = EditorGUI.Foldout( searchedObjectsHeaderRect, drawObjectsToSearchSection, GUIContent.none, true );
|
||||||
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Start searching
|
if( drawObjectsToSearchSection )
|
||||||
searchResult = core.Run( new AssetUsageDetector.Parameters()
|
objectsToSearchDrawer.Draw( objectsToSearch );
|
||||||
{
|
}
|
||||||
objectsToSearch = new ObjectToSearchEnumerator( objectsToSearch ).ToArray(),
|
|
||||||
searchInScenes = GetSceneSearchMode( true ),
|
private void BeginIndentedGUI( bool isVertical = true )
|
||||||
searchInAssetsFolder = searchInAssetsFolder,
|
{
|
||||||
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
|
GUILayout.BeginHorizontal();
|
||||||
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
|
GUILayout.Space( 35f );
|
||||||
dontSearchInSourceAssets = dontSearchInSourceAssets,
|
|
||||||
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
|
if( isVertical )
|
||||||
searchInProjectSettings = searchInProjectSettings,
|
GUILayout.BeginVertical();
|
||||||
//fieldModifiers = fieldModifiers,
|
}
|
||||||
//propertyModifiers = propertyModifiers,
|
|
||||||
//searchDepthLimit = searchDepthLimit,
|
private void EndIndentedGUI( bool isVertical = true )
|
||||||
//searchNonSerializableVariables = searchNonSerializableVariables,
|
{
|
||||||
lazySceneSearch = lazySceneSearch,
|
if( isVertical )
|
||||||
noAssetDatabaseChanges = noAssetDatabaseChanges,
|
GUILayout.EndVertical();
|
||||||
showDetailedProgressBar = showDetailedProgressBar
|
|
||||||
} );
|
GUILayout.EndHorizontal();
|
||||||
|
}
|
||||||
currentPhase = Phase.Complete;
|
|
||||||
}
|
public static bool WordWrappingToggleLeft( string label, bool value )
|
||||||
|
{
|
||||||
|
sharedGUIContent.text = label;
|
||||||
|
sharedGUIContent.tooltip = null;
|
||||||
|
return WordWrappingToggleLeft( sharedGUIContent, value );
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool WordWrappingToggleLeft( GUIContent label, bool value )
|
||||||
|
{
|
||||||
|
GUILayout.BeginHorizontal();
|
||||||
|
bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 );
|
||||||
|
if( GUILayout.Button( label, EditorStyles.wordWrappedLabel ) )
|
||||||
|
{
|
||||||
|
GUI.FocusControl( null );
|
||||||
|
result = !value;
|
||||||
|
}
|
||||||
|
GUILayout.EndHorizontal();
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void InitiateSearch()
|
||||||
|
{
|
||||||
|
currentPhase = Phase.Processing;
|
||||||
|
|
||||||
|
SavePrefs();
|
||||||
|
ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
|
||||||
|
|
||||||
|
// Start searching
|
||||||
|
searchResult = core.Run( new AssetUsageDetector.Parameters()
|
||||||
|
{
|
||||||
|
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
|
||||||
|
searchInScenes = GetSceneSearchMode( true ),
|
||||||
|
searchInSceneLightingSettings = searchInSceneLightingSettings,
|
||||||
|
searchInAssetsFolder = searchInAssetsFolder,
|
||||||
|
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
|
||||||
|
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
|
||||||
|
dontSearchInSourceAssets = dontSearchInSourceAssets,
|
||||||
|
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
|
||||||
|
searchInProjectSettings = searchInProjectSettings,
|
||||||
|
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
|
||||||
|
searchRefactoring = searchRefactoring,
|
||||||
|
#if ASSET_USAGE_ADDRESSABLES
|
||||||
|
lazySceneSearch = lazySceneSearch && !addressablesSupport,
|
||||||
|
addressablesSupport = addressablesSupport,
|
||||||
|
#else
|
||||||
|
lazySceneSearch = lazySceneSearch,
|
||||||
|
#endif
|
||||||
|
calculateUnusedObjects = calculateUnusedObjects,
|
||||||
|
hideDuplicateRows = hideDuplicateRows,
|
||||||
|
hideRedundantPrefabReferencesInAssets = hideRedundantPrefabReferencesInAssets,
|
||||||
|
hideRedundantPrefabReferencesInScenes = hideRedundantPrefabReferencesInScenes && searchInAssetsFolder,
|
||||||
|
noAssetDatabaseChanges = noAssetDatabaseChanges,
|
||||||
|
showDetailedProgressBar = showDetailedProgressBar
|
||||||
|
} );
|
||||||
|
|
||||||
|
currentPhase = Phase.Complete;
|
||||||
|
|
||||||
|
// We really don't want SearchRefactoring to affect next searches unless the search is initiated via ShowAndSearch again
|
||||||
|
searchRefactoring = null;
|
||||||
|
|
||||||
|
if( AssetUsageDetectorSettings.ShowCustomTooltip )
|
||||||
|
wantsMouseMove = wantsMouseEnterLeaveWindow = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
|
// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
|
||||||
public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
|
public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
|
||||||
{
|
{
|
||||||
if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
|
if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
|
||||||
return;
|
return;
|
||||||
|
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
|
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
|
||||||
#else
|
|
||||||
GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
|
|
||||||
#endif
|
|
||||||
if( prefabAsset == null || prefabAsset.Equals( null ) )
|
if( prefabAsset == null || prefabAsset.Equals( null ) )
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -731,19 +718,36 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
private bool ReturnToSetupPhase( bool restoreInitialSceneSetup, bool sceneSetupRestorationIsOptional )
|
private bool ReturnToSetupPhase()
|
||||||
{
|
{
|
||||||
if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup( sceneSetupRestorationIsOptional ) )
|
if( searchResult != null && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
searchResult = null;
|
searchResult = null;
|
||||||
|
|
||||||
errorMessage = string.Empty;
|
|
||||||
currentPhase = Phase.Setup;
|
currentPhase = Phase.Setup;
|
||||||
|
wantsMouseMove = wantsMouseEnterLeaveWindow = false;
|
||||||
|
|
||||||
|
SearchResultTooltip.Hide();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void OnSettingsChanged( bool highlightedSearchTextColorChanged = false, bool tooltipDescriptionsColorChanged = false )
|
||||||
|
{
|
||||||
|
if( searchResult == null )
|
||||||
|
return;
|
||||||
|
|
||||||
|
wantsMouseMove = wantsMouseEnterLeaveWindow = AssetUsageDetectorSettings.ShowCustomTooltip;
|
||||||
|
|
||||||
|
for( int i = searchResult.NumberOfGroups - 1; i >= 0; i-- )
|
||||||
|
{
|
||||||
|
if( searchResult[i].treeView != null )
|
||||||
|
{
|
||||||
|
searchResult[i].treeView.rowHeight = EditorGUIUtility.singleLineHeight + AssetUsageDetectorSettings.ExtraRowHeight;
|
||||||
|
searchResult[i].treeView.OnSettingsChanged( highlightedSearchTextColorChanged, tooltipDescriptionsColorChanged );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,8 +31,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
{
|
{
|
||||||
// Handle drag & drop references to array
|
// Handle drag & drop references to array
|
||||||
// Credit: https://answers.unity.com/answers/657877/view.html
|
// Credit: https://answers.unity.com/answers/657877/view.html
|
||||||
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) &&
|
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
|
||||||
GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
|
|
||||||
{
|
{
|
||||||
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
|
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
|
||||||
if( ev.type == EventType.DragPerform )
|
if( ev.type == EventType.DragPerform )
|
||||||
@@ -69,6 +68,18 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
ev.Use();
|
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 ) )
|
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
|
||||||
list.Insert( 0, CreateElement( null ) );
|
list.Insert( 0, CreateElement( null ) );
|
||||||
@@ -86,7 +97,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
Object prevObject = GetObjectFromElement( element );
|
Object prevObject = GetObjectFromElement( element );
|
||||||
Object newObject = EditorGUILayout.ObjectField( "", prevObject, typeof( Object ), acceptSceneObjects );
|
Object newObject = EditorGUILayout.ObjectField( "", prevObject, typeof( Object ), acceptSceneObjects );
|
||||||
|
|
||||||
if( GUI.changed && prevObject != newObject )
|
if( GUI.changed )
|
||||||
{
|
{
|
||||||
hasChanged = true;
|
hasChanged = true;
|
||||||
SetObjectOfElement( list, i, newObject );
|
SetObjectOfElement( list, i, newObject );
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
using UnityEngine.U2D;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
|
|
||||||
namespace AssetUsageDetectorNamespace
|
namespace AssetUsageDetectorNamespace
|
||||||
@@ -26,7 +27,6 @@ namespace AssetUsageDetectorNamespace
|
|||||||
public List<SubAsset> subAssets;
|
public List<SubAsset> subAssets;
|
||||||
public bool showSubAssetsFoldout;
|
public bool showSubAssetsFoldout;
|
||||||
|
|
||||||
private static MonoScript[] monoScriptsInProject;
|
|
||||||
private static HashSet<Object> currentSubAssets;
|
private static HashSet<Object> currentSubAssets;
|
||||||
|
|
||||||
public ObjectToSearch( Object obj, bool? shouldSearchChildren = null )
|
public ObjectToSearch( Object obj, bool? shouldSearchChildren = null )
|
||||||
@@ -81,11 +81,8 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
if( includeTarget )
|
if( includeTarget )
|
||||||
{
|
{
|
||||||
if( !currentSubAssets.Contains( target ) )
|
if( currentSubAssets.Add( target ) )
|
||||||
{
|
|
||||||
subAssets.Add( new SubAsset( target, shouldSearchChildren ?? true ) );
|
subAssets.Add( new SubAsset( target, shouldSearchChildren ?? true ) );
|
||||||
currentSubAssets.Add( target );
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -99,54 +96,32 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add Sprites of SpriteAtlases to the sub-assets list
|
||||||
|
if( target is SpriteAtlas spriteAtlas )
|
||||||
|
{
|
||||||
|
foreach (Sprite sprite in spriteAtlas.GetPackedSprites())
|
||||||
|
{
|
||||||
|
if (sprite != null && currentSubAssets.Add(sprite))
|
||||||
|
subAssets.Add(new SubAsset(sprite, shouldSearchChildren ?? true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Find sub-asset(s) of the asset (if any)
|
// Find sub-asset(s) of the asset (if any)
|
||||||
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
|
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
|
||||||
for( int i = 0; i < assets.Length; i++ )
|
for( int i = 0; i < assets.Length; i++ )
|
||||||
{
|
{
|
||||||
Object asset = assets[i];
|
Object asset = assets[i];
|
||||||
if( asset == null || asset.Equals( null ) || asset is Component )
|
if( asset == null || asset.Equals( null ) || asset is Component || asset == target )
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
if( currentSubAssets.Contains( asset ) )
|
// 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;
|
continue;
|
||||||
|
|
||||||
if( asset != target )
|
if( currentSubAssets.Add( asset ) )
|
||||||
{
|
|
||||||
subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) );
|
subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) );
|
||||||
currentSubAssets.Add( asset );
|
|
||||||
}
|
|
||||||
|
|
||||||
// MonoScripts are a special case such that other MonoScript objects
|
|
||||||
// that extend this MonoScript are also considered a sub-asset
|
|
||||||
if( asset is MonoScript )
|
|
||||||
{
|
|
||||||
Type monoScriptType = ( (MonoScript) asset ).GetClass();
|
|
||||||
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
|
|
||||||
continue;
|
|
||||||
|
|
||||||
// Find all MonoScript objects in the project
|
|
||||||
if( monoScriptsInProject == null )
|
|
||||||
{
|
|
||||||
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
|
|
||||||
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
|
|
||||||
for( int k = 0; k < monoScriptGuids.Length; k++ )
|
|
||||||
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add any MonoScript objects that extend this MonoScript as a sub-asset
|
|
||||||
for( int j = 0; j < monoScriptsInProject.Length; j++ )
|
|
||||||
{
|
|
||||||
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
|
|
||||||
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
|
|
||||||
{
|
|
||||||
subAssets.Add( new SubAsset( monoScriptsInProject[j], shouldSearchChildren ?? true ) );
|
|
||||||
currentSubAssets.Add( monoScriptsInProject[j] );
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,375 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using UnityEditor;
|
||||||
|
using UnityEditor.SceneManagement;
|
||||||
|
using UnityEngine;
|
||||||
|
using UnityEngine.Rendering;
|
||||||
|
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].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 = shader.GetPropertyCount();
|
||||||
|
for( int i = 0; i < shaderPropertyCount; i++ )
|
||||||
|
{
|
||||||
|
if (shader.GetPropertyType(i) != ShaderPropertyType.Texture)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
string propertyName = shader.GetPropertyName(i);
|
||||||
|
if ((shader.GetPropertyFlags(i) & ShaderPropertyFlags.NonModifiableTextureData) != 0)
|
||||||
|
{
|
||||||
|
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:
|
||||||
@@ -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:
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: b3903f1d3149e9b4990e49206f8255c8
|
||||||
|
timeCreated: 1638690728
|
||||||
|
licenseType: Free
|
||||||
|
MonoImporter:
|
||||||
|
serializedVersion: 2
|
||||||
|
defaultReferences: []
|
||||||
|
executionOrder: 0
|
||||||
|
icon: {instanceID: 0}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
@@ -2,18 +2,15 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
#if UNITY_2018_1_OR_NEWER
|
using System.Threading.Tasks;
|
||||||
using Unity.Collections;
|
using Unity.Collections;
|
||||||
#endif
|
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEditor.SceneManagement;
|
using UnityEditor.SceneManagement;
|
||||||
|
using UnityEditor.U2D;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEngine.SceneManagement;
|
using UnityEngine.SceneManagement;
|
||||||
|
using UnityEngine.U2D;
|
||||||
using Object = UnityEngine.Object;
|
using Object = UnityEngine.Object;
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
|
|
||||||
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace AssetUsageDetectorNamespace
|
namespace AssetUsageDetectorNamespace
|
||||||
{
|
{
|
||||||
@@ -37,26 +34,23 @@ namespace AssetUsageDetectorNamespace
|
|||||||
typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ),
|
typeof( List<Vector4> ), typeof( List<Vector3> ), typeof( List<Vector2> ), typeof( List<Rect> ),
|
||||||
typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ), typeof( List<Bounds> ),
|
typeof( List<Quaternion> ), typeof( List<Color> ), typeof( List<Color32> ), typeof( List<LayerMask> ), typeof( List<Bounds> ),
|
||||||
typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> ),
|
typeof( List<Matrix4x4> ), typeof( List<AnimationCurve> ), typeof( List<Gradient> ), typeof( List<RectOffset> ),
|
||||||
#if UNITY_2017_2_OR_NEWER
|
|
||||||
typeof( Vector3Int ), typeof( Vector2Int ), typeof( RectInt ), typeof( BoundsInt ),
|
typeof( Vector3Int ), typeof( Vector2Int ), typeof( RectInt ), typeof( BoundsInt ),
|
||||||
typeof( Vector3Int[] ), typeof( Vector2Int[] ), typeof( RectInt[] ), typeof( BoundsInt[] ),
|
typeof( Vector3Int[] ), typeof( Vector2Int[] ), typeof( RectInt[] ), typeof( BoundsInt[] ),
|
||||||
typeof( List<Vector3Int> ), typeof( List<Vector2Int> ), typeof( List<RectInt> ), typeof( List<BoundsInt> )
|
typeof( List<Vector3Int> ), typeof( List<Vector2Int> ), typeof( List<RectInt> ), typeof( List<BoundsInt> )
|
||||||
#endif
|
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
|
private static readonly string reflectionNamespace = typeof( Assembly ).Namespace;
|
||||||
#if UNITY_2018_1_OR_NEWER
|
|
||||||
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
|
private static readonly string nativeCollectionsNamespace = typeof( NativeArray<int> ).Namespace;
|
||||||
#endif
|
|
||||||
|
private static MethodInfo screenFittedRectGetter;
|
||||||
|
private static FieldInfo editorWindowHostViewGetter;
|
||||||
|
private static PropertyInfo hostViewContainerWindowGetter;
|
||||||
|
|
||||||
|
private static readonly Func<Object, bool, bool> prefabHasAnyOverridesGetter = (Func<Object, bool, bool>) Delegate.CreateDelegate( typeof( Func<Object, bool, bool> ), typeof( PrefabUtility ).GetMethod( "HasObjectOverride", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ) );
|
||||||
|
|
||||||
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
|
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
|
||||||
|
|
||||||
private static readonly StringBuilder stringBuilder = new StringBuilder( 10 );
|
internal static readonly StringBuilder stringBuilder = new StringBuilder( 400 );
|
||||||
|
|
||||||
#if UNITY_2018_3_OR_NEWER
|
|
||||||
private static int previousPingedPrefabInstanceId;
|
|
||||||
private static double previousPingedPrefabPingTime;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true );
|
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_EXPAND_HEIGHT = GUILayout.ExpandHeight( true );
|
||||||
@@ -79,72 +73,132 @@ namespace AssetUsageDetectorNamespace
|
|||||||
m_boxGUIStyle = new GUIStyle( EditorStyles.helpBox )
|
m_boxGUIStyle = new GUIStyle( EditorStyles.helpBox )
|
||||||
{
|
{
|
||||||
alignment = TextAnchor.MiddleCenter,
|
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;
|
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.scaledBackgrounds = new Texture2D[0];
|
|
||||||
normalState.textColor = Color.black;
|
|
||||||
}
|
|
||||||
|
|
||||||
if( normalState.background == null || normalState.background.Equals( null ) )
|
|
||||||
{
|
|
||||||
Texture2D backgroundTexture = new Texture2D( 1, 1 ) { hideFlags = HideFlags.HideAndDontSave };
|
|
||||||
backgroundTexture.SetPixel( 0, 0, new Color( 0.88f, 0.88f, 0.88f, 0.85f ) );
|
|
||||||
backgroundTexture.Apply();
|
|
||||||
|
|
||||||
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
|
// Check if object is an asset or a Scene object
|
||||||
public static bool IsAsset( this object obj )
|
public static bool IsAsset( this object obj )
|
||||||
{
|
{
|
||||||
return obj is Object && AssetDatabase.Contains( (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
|
// Check if object is a folder asset
|
||||||
public static bool IsFolder( this Object obj )
|
public static bool IsFolder( this Object obj )
|
||||||
{
|
{
|
||||||
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
|
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static T GetPrefabParent<T>( this T obj ) where T : Object
|
||||||
|
{
|
||||||
|
return PrefabUtility.GetCorrespondingObjectFromSource( obj );
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool HasAnyPrefabOverrides( this Object obj )
|
||||||
|
{
|
||||||
|
if( obj.GetPrefabParent() == null )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return prefabHasAnyOverridesGetter( obj, false );
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool HasAnyPrefabOverrides( this GameObject gameObject )
|
||||||
|
{
|
||||||
|
if( gameObject.GetPrefabParent() == null )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if( !PrefabUtility.HasPrefabInstanceAnyOverrides( gameObject, false ) )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
Transform rootTransform = gameObject.transform;
|
||||||
|
List<Component> components = new List<Component>( 8 );
|
||||||
|
Stack<Transform> stack = new Stack<Transform>( 8 );
|
||||||
|
stack.Push( rootTransform );
|
||||||
|
|
||||||
|
while( stack.Count > 0 )
|
||||||
|
{
|
||||||
|
Transform transform = stack.Pop();
|
||||||
|
Transform prefab = transform.GetPrefabParent();
|
||||||
|
if( prefab == null ) // GameObject is added as override
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if( transform.childCount != prefab.childCount ) // Has some added/destroyed children as override
|
||||||
|
return true;
|
||||||
|
|
||||||
|
bool isRootTransform = ReferenceEquals( transform, rootTransform );
|
||||||
|
if( !isRootTransform && ( transform.gameObject as Object ).HasAnyPrefabOverrides() ) // GameObject's properties are modified (e.g. name or tag) (excluding root GameObject)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
components.Clear();
|
||||||
|
transform.GetComponents( components );
|
||||||
|
foreach( Component component in components )
|
||||||
|
{
|
||||||
|
if( component == null )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if( component.GetPrefabParent() == null ) // Component is added as override
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if( ( !isRootTransform || !( component is Transform ) ) && component.HasAnyPrefabOverrides() ) // Component is modified (excluding root Transform)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int componentCount = components.Count;
|
||||||
|
components.Clear();
|
||||||
|
prefab.GetComponents( components );
|
||||||
|
if( components.Count != componentCount ) // Has some destroyed components as override
|
||||||
|
return true;
|
||||||
|
|
||||||
|
for( int i = 0, childCount = transform.childCount; i < childCount; i++ )
|
||||||
|
{
|
||||||
|
Transform child = transform.GetChild( i );
|
||||||
|
if( child != null )
|
||||||
|
stack.Push( child );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if UNITY_6000_3_OR_NEWER
|
||||||
|
public static EntityId GetEntityId(this Object obj)
|
||||||
|
{
|
||||||
|
return obj.GetEntityId();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object EntityIdToObject(EntityId entityId)
|
||||||
|
{
|
||||||
|
return EditorUtility.EntityIdToObject(entityId);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
public static int GetEntityId(this Object obj)
|
||||||
|
{
|
||||||
|
return obj.GetInstanceID();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object EntityIdToObject(int instanceID)
|
||||||
|
{
|
||||||
|
return EditorUtility.InstanceIDToObject(instanceID);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
// Returns an enumerator to iterate through all asset paths in the folder
|
// Returns an enumerator to iterate through all asset paths in the folder
|
||||||
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
|
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
|
||||||
{
|
{
|
||||||
@@ -163,134 +217,64 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return folderContentsSet;
|
return folderContentsSet;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Select an object in the editor
|
public static void GetObjectsToSelectAndPing( this Object obj, out Object selection, out Object pingTarget )
|
||||||
public static void SelectInEditor( this Object obj )
|
|
||||||
{
|
{
|
||||||
if( obj == null )
|
if( obj == null || obj.Equals( null ) )
|
||||||
return;
|
|
||||||
|
|
||||||
Event e = Event.current;
|
|
||||||
|
|
||||||
// If CTRL or Shift keys are pressed, do a multi-select;
|
|
||||||
// otherwise select only the clicked object and ping it in editor
|
|
||||||
if( !e.control && !e.shift )
|
|
||||||
Selection.activeObject = obj.PingInEditor();
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
Component objAsComp = obj as Component;
|
selection = pingTarget = null;
|
||||||
GameObject objAsGO = obj as GameObject;
|
return;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Ping an object in either Project view or Hierarchy view
|
|
||||||
public static Object PingInEditor( this Object obj )
|
|
||||||
{
|
|
||||||
if( obj is Component )
|
if( obj is Component )
|
||||||
obj = ( (Component) obj ).gameObject;
|
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
|
if( obj.IsAsset() )
|
||||||
// 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 UNITY_2018_3_OR_NEWER
|
if( obj is GameObject )
|
||||||
Transform objTR = ( (GameObject) obj ).transform.root;
|
|
||||||
|
|
||||||
PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject );
|
|
||||||
if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant )
|
|
||||||
{
|
{
|
||||||
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
|
// Pinging a prefab only works if the pinged object is the root of the prefab or a direct child of it. Pinging any grandchildren
|
||||||
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
|
// 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;
|
||||||
|
|
||||||
// Try to open the prefab stage of pinged prefabs if they are double clicked
|
PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject );
|
||||||
if( previousPingedPrefabInstanceId == objTR.GetInstanceID() && EditorApplication.timeSinceStartup - previousPingedPrefabPingTime <= 0.3f &&
|
if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant )
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath ) )
|
|
||||||
#else
|
|
||||||
( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.prefabAssetPath ) )
|
|
||||||
#endif
|
|
||||||
{
|
{
|
||||||
AssetDatabase.OpenAsset( objTR.gameObject );
|
string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject );
|
||||||
openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
|
PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage();
|
||||||
}
|
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath )
|
||||||
|
|
||||||
previousPingedPrefabInstanceId = objTR.GetInstanceID();
|
|
||||||
previousPingedPrefabPingTime = EditorApplication.timeSinceStartup;
|
|
||||||
|
|
||||||
#if UNITY_2020_1_OR_NEWER
|
|
||||||
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath )
|
|
||||||
#else
|
|
||||||
if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath )
|
|
||||||
#endif
|
|
||||||
{
|
|
||||||
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot );
|
|
||||||
if( prefabStageGO != null )
|
|
||||||
{
|
{
|
||||||
objTR = prefabStageGO.transform;
|
GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot );
|
||||||
selection = objTR.gameObject;
|
if( prefabStageGO != null )
|
||||||
|
{
|
||||||
|
objTR = prefabStageGO.transform;
|
||||||
|
selection = objTR.gameObject;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
else if( obj != objTR.gameObject )
|
||||||
|
selection = objTR.gameObject;
|
||||||
}
|
}
|
||||||
#if UNITY_2019_1_OR_NEWER
|
else if( prefabAssetType == PrefabAssetType.Model )
|
||||||
else if( obj != objTR.gameObject )
|
|
||||||
{
|
{
|
||||||
Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name );
|
objTR = ( (GameObject) obj ).transform;
|
||||||
selection = objTR.gameObject;
|
while( objTR.parent != null && objTR.parent.parent != null )
|
||||||
|
objTR = objTR.parent;
|
||||||
}
|
}
|
||||||
#else
|
|
||||||
else
|
pingTarget = objTR.gameObject;
|
||||||
Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name );
|
}
|
||||||
#endif
|
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 ) );
|
||||||
}
|
}
|
||||||
#else
|
|
||||||
Transform objTR = ( (GameObject) obj ).transform;
|
|
||||||
while( objTR.parent != null && objTR.parent.parent != null )
|
|
||||||
objTR = objTR.parent;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
obj = objTR.gameObject;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
EditorGUIUtility.PingObject( obj );
|
|
||||||
return selection;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// We are passing "go"s root Transform to thisRoot parameter. If we use go.transform.root instead, when we are in prefab mode on
|
// We are passing "go"s root Transform to thisRoot parameter. If we use go.transform.root instead, when we are in prefab mode on
|
||||||
@@ -327,76 +311,41 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return root2.gameObject;
|
return root2.gameObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the field is serializable
|
// 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 bool IsSerializable( this FieldInfo fieldInfo )
|
public static int CompareHierarchySiblingIndices( Transform t1, Transform t2 )
|
||||||
{
|
{
|
||||||
// See Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
|
Transform parent1 = t1.parent;
|
||||||
if( fieldInfo.IsInitOnly )
|
Transform parent2 = t2.parent;
|
||||||
return false;
|
|
||||||
|
|
||||||
#if UNITY_2019_3_OR_NEWER
|
if( parent1 == parent2 )
|
||||||
// SerializeReference makes even System.Object fields serializable
|
return t1.GetSiblingIndex() - t2.GetSiblingIndex();
|
||||||
if( Attribute.IsDefined( fieldInfo, typeof( SerializeReference ) ) )
|
|
||||||
return true;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) && !Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) )
|
int deltaHierarchyDepth = 0;
|
||||||
return false;
|
for( ; parent1; parent1 = parent1.parent )
|
||||||
|
deltaHierarchyDepth++;
|
||||||
|
for( ; parent2; parent2 = parent2.parent )
|
||||||
|
deltaHierarchyDepth--;
|
||||||
|
|
||||||
return IsTypeSerializable( fieldInfo.FieldType );
|
for( ; deltaHierarchyDepth > 0; deltaHierarchyDepth-- )
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the property is serializable
|
|
||||||
public static bool IsSerializable( this PropertyInfo propertyInfo )
|
|
||||||
{
|
|
||||||
return IsTypeSerializable( propertyInfo.PropertyType );
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if type is serializable
|
|
||||||
private static bool IsTypeSerializable( Type type )
|
|
||||||
{
|
|
||||||
// see Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
|
|
||||||
if( typeof( Object ).IsAssignableFrom( type ) )
|
|
||||||
return true;
|
|
||||||
|
|
||||||
if( type.IsArray )
|
|
||||||
{
|
{
|
||||||
if( type.GetArrayRank() != 1 )
|
t1 = t1.parent;
|
||||||
return false;
|
if( t1 == t2 )
|
||||||
|
return 1;
|
||||||
type = type.GetElementType();
|
|
||||||
|
|
||||||
if( typeof( Object ).IsAssignableFrom( type ) )
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
else if( type.IsGenericType )
|
for( ; deltaHierarchyDepth < 0; deltaHierarchyDepth++ )
|
||||||
{
|
{
|
||||||
// Generic types are allowed on 2020.1 and later
|
t2 = t2.parent;
|
||||||
#if UNITY_2020_1_OR_NEWER
|
if( t1 == t2 )
|
||||||
if( type.GetGenericTypeDefinition() == typeof( List<> ) )
|
return -1;
|
||||||
{
|
|
||||||
type = type.GetGenericArguments()[0];
|
|
||||||
|
|
||||||
if( typeof( Object ).IsAssignableFrom( type ) )
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
if( type.GetGenericTypeDefinition() != typeof( List<> ) )
|
|
||||||
return false;
|
|
||||||
|
|
||||||
type = type.GetGenericArguments()[0];
|
|
||||||
|
|
||||||
if( typeof( Object ).IsAssignableFrom( type ) )
|
|
||||||
return true;
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#if !UNITY_2020_1_OR_NEWER
|
while( t1.parent != t2.parent )
|
||||||
if( type.IsGenericType )
|
{
|
||||||
return false;
|
t1 = t1.parent;
|
||||||
#endif
|
t2 = t2.parent;
|
||||||
|
}
|
||||||
|
|
||||||
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
|
return t1.GetSiblingIndex() - t2.GetSiblingIndex();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if instances of this type should be searched for references
|
// Check if instances of this type should be searched for references
|
||||||
@@ -405,19 +354,21 @@ namespace AssetUsageDetectorNamespace
|
|||||||
if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum )
|
if( type.IsPrimitive || primitiveUnityTypes.Contains( type ) || type.IsEnum )
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
#if UNITY_2018_1_OR_NEWER
|
|
||||||
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
|
// Searching NativeArrays for reference can throw InvalidOperationException if the collection is disposed
|
||||||
if( type.Namespace == nativeCollectionsNamespace )
|
if( type.Namespace == nativeCollectionsNamespace )
|
||||||
return true;
|
return true;
|
||||||
#endif
|
|
||||||
|
|
||||||
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
|
// Searching assembly variables for reference throws InvalidCastException on .NET 4.0 runtime
|
||||||
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
|
if( typeof( Type ).IsAssignableFrom( type ) || type.Namespace == reflectionNamespace )
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
// Searching pointers or ref variables for reference throws ArgumentException
|
// Searching Tasks for reference may freeze Unity since Task.Result freezes the active thread if Task hasn't completed yet
|
||||||
if( type.IsPointer || type.IsByRef )
|
if (typeof(Task).IsAssignableFrom(type))
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
|
// Searching pointers, ref variables or ref structs for reference throws ArgumentException
|
||||||
|
if (type.IsPointer || type.IsByRef || type.IsByRefLike)
|
||||||
|
return true;
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -446,7 +397,20 @@ namespace AssetUsageDetectorNamespace
|
|||||||
{
|
{
|
||||||
// Can't use PropertyWrapper (which uses CreateDelegate) for property getters of structs
|
// Can't use PropertyWrapper (which uses CreateDelegate) for property getters of structs
|
||||||
if( propertyInfo.DeclaringType.IsValueType )
|
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 );
|
Type GenType = typeof( PropertyWrapper<,> ).MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType );
|
||||||
return ( (IPropertyAccessor) Activator.CreateInstance( GenType, propertyInfo.GetGetMethod( true ) ) ).GetValue;
|
return ( (IPropertyAccessor) Activator.CreateInstance( GenType, propertyInfo.GetGetMethod( true ) ) ).GetValue;
|
||||||
@@ -455,9 +419,9 @@ namespace AssetUsageDetectorNamespace
|
|||||||
// Check if all open scenes are saved (not dirty)
|
// Check if all open scenes are saved (not dirty)
|
||||||
public static bool AreScenesSaved()
|
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 ) )
|
if( scene.isDirty || string.IsNullOrEmpty( scene.path ) )
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -485,14 +449,43 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return stringBuilder.ToString();
|
return stringBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Draw header inside OnGUI
|
||||||
|
public static void DrawHeader( string label )
|
||||||
|
{
|
||||||
|
Color c = GUI.backgroundColor;
|
||||||
|
GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
|
||||||
|
GUILayout.Box( label, BoxGUIStyle, GL_EXPAND_WIDTH );
|
||||||
|
GUI.backgroundColor = c;
|
||||||
|
}
|
||||||
|
|
||||||
// Draw horizontal line inside OnGUI
|
// Draw horizontal line inside OnGUI
|
||||||
public static void DrawSeparatorLine()
|
public static void DrawSeparatorLine()
|
||||||
{
|
{
|
||||||
GUILayout.Space( 4 );
|
GUILayout.Space( 4f );
|
||||||
GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH );
|
GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH );
|
||||||
GUILayout.Space( 4 );
|
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
|
// Check if all the objects inside the list are null
|
||||||
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
|
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
|
||||||
{
|
{
|
||||||
@@ -501,7 +494,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
|
|
||||||
for( int i = 0; i < objectsToSearch.Count; i++ )
|
for( int i = 0; i < objectsToSearch.Count; i++ )
|
||||||
{
|
{
|
||||||
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) )
|
if( objectsToSearch[i].obj != null )
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -509,38 +502,20 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if all the objects inside the list are null
|
// Check if all the objects inside the list are null
|
||||||
public static bool IsEmpty( this List<Object> objects )
|
public static bool IsEmpty<T>( this List<T> objects ) where T : Object
|
||||||
{
|
{
|
||||||
if( objects == null )
|
if( objects == null )
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
for( int i = 0; i < objects.Count; i++ )
|
for( int i = 0; i < objects.Count; i++ )
|
||||||
{
|
{
|
||||||
if( objects[i] != null && !objects[i].Equals( null ) )
|
if( objects[i] != null )
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if all the objects that are enumerated are null
|
|
||||||
public static bool IsEmpty( this IEnumerable<Object> objects )
|
|
||||||
{
|
|
||||||
if( objects == null )
|
|
||||||
return true;
|
|
||||||
|
|
||||||
using( IEnumerator<Object> enumerator = objects.GetEnumerator() )
|
|
||||||
{
|
|
||||||
while( enumerator.MoveNext() )
|
|
||||||
{
|
|
||||||
if( enumerator.Current != null && !enumerator.Current.Equals( null ) )
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns true is str starts with prefix
|
// Returns true is str starts with prefix
|
||||||
public static bool StartsWithFast( this string str, string prefix )
|
public static bool StartsWithFast( this string str, string prefix )
|
||||||
{
|
{
|
||||||
@@ -592,12 +567,41 @@ namespace AssetUsageDetectorNamespace
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void RemoveAtFast<T>( this List<T> list, int index )
|
public static List<Sprite> GetPackedSprites(this SpriteAtlas spriteAtlas)
|
||||||
{
|
{
|
||||||
int lastElementIndex = list.Count - 1;
|
SpriteAtlas masterAtlas = spriteAtlas.isVariant ? spriteAtlas.GetMasterAtlas() : null;
|
||||||
|
Object[] packables = (masterAtlas != null) ? masterAtlas.GetPackables() : spriteAtlas.GetPackables();
|
||||||
|
List<Sprite> result = new(packables.Length);
|
||||||
|
|
||||||
list[index] = list[lastElementIndex];
|
foreach (Object packable in packables)
|
||||||
list.RemoveAt( lastElementIndex );
|
{
|
||||||
|
if (packable == null)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if (packable.IsFolder())
|
||||||
|
{
|
||||||
|
foreach (string guid in AssetDatabase.FindAssets("t:Sprite", new[] { AssetDatabase.GetAssetPath(packable) }))
|
||||||
|
{
|
||||||
|
foreach (Object asset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GUIDToAssetPath(guid)))
|
||||||
|
{
|
||||||
|
if (asset is Sprite sprite)
|
||||||
|
result.Add(sprite);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (packable is Texture2D)
|
||||||
|
{
|
||||||
|
foreach (Object asset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(packable)))
|
||||||
|
{
|
||||||
|
if (asset is Sprite sprite)
|
||||||
|
result.Add(sprite);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (packable is Sprite sprite)
|
||||||
|
result.Add(sprite);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace AssetUsageDetectorNamespace
|
namespace AssetUsageDetectorNamespace
|
||||||
@@ -8,30 +9,27 @@ namespace AssetUsageDetectorNamespace
|
|||||||
public delegate object VariableGetVal( object obj );
|
public delegate object VariableGetVal( object obj );
|
||||||
|
|
||||||
// Custom struct to hold a variable, its important properties and its getter function
|
// Custom struct to hold a variable, its important properties and its getter function
|
||||||
public struct VariableGetterHolder
|
public readonly struct VariableGetterHolder
|
||||||
{
|
{
|
||||||
public readonly string name;
|
public readonly MemberInfo variable;
|
||||||
public readonly bool isProperty;
|
|
||||||
public readonly bool isSerializable;
|
|
||||||
private readonly VariableGetVal getter;
|
private readonly VariableGetVal getter;
|
||||||
|
|
||||||
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
|
public readonly string Name { get { return variable.Name; } }
|
||||||
{
|
public readonly bool IsProperty { get { return variable is PropertyInfo; } }
|
||||||
name = fieldInfo.Name;
|
|
||||||
isProperty = false;
|
|
||||||
this.isSerializable = isSerializable;
|
|
||||||
this.getter = getter;
|
|
||||||
}
|
|
||||||
|
|
||||||
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
|
public VariableGetterHolder(FieldInfo fieldInfo, VariableGetVal getter)
|
||||||
{
|
{
|
||||||
name = propertyInfo.Name;
|
this.variable = fieldInfo;
|
||||||
isProperty = true;
|
this.getter = getter;
|
||||||
this.isSerializable = isSerializable;
|
}
|
||||||
this.getter = getter;
|
|
||||||
}
|
|
||||||
|
|
||||||
public object Get( object obj )
|
public VariableGetterHolder(PropertyInfo propertyInfo, VariableGetVal getter)
|
||||||
|
{
|
||||||
|
this.variable = propertyInfo;
|
||||||
|
this.getter = getter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public readonly object Get( object obj )
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -39,7 +37,12 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
catch( Exception e )
|
catch( Exception e )
|
||||||
{
|
{
|
||||||
Debug.LogException( e );
|
StringBuilder sb = Utilities.stringBuilder;
|
||||||
|
sb.Length = 0;
|
||||||
|
sb.Append( "Error while getting the value of (" ).Append( IsProperty ? ( (PropertyInfo) variable ).PropertyType : ( (FieldInfo) variable ).FieldType ).Append( ") " )
|
||||||
|
.Append( variable.DeclaringType ).Append( "." ).Append( Name ).Append( ": " ).Append( e );
|
||||||
|
|
||||||
|
Debug.LogError( sb.ToString() );
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -69,8 +72,7 @@ namespace AssetUsageDetectorNamespace
|
|||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
// Property getters may return various kinds of exceptions
|
// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
|
||||||
// if their backing fields are not initialized (yet)
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,4 @@
|
|||||||
= Asset Usage Detector =
|
= Asset Usage Detector (v2.6.3) =
|
||||||
|
|
||||||
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
|
Documentation: https://github.com/yasirkula/UnityAssetUsageDetector
|
||||||
E-mail: yasirkula@gmail.com
|
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 right click an object and select "Search For References".
|
|
||||||
|
|
||||||
In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the
|
|
||||||
references are formed. If a node's label contains text inside square brackets (e.g. [Child object]), then that text describes how that node is
|
|
||||||
connected to the node to its left.
|
|
||||||
|
|
||||||
3. KNOWN LIMITATIONS
|
|
||||||
- static variables are not searched
|
|
||||||
- GUIText materials are not searched
|
|
||||||
- Textures in Lens Flare's can not be searched
|
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "com.yasirkula.assetusagedetector",
|
"name": "com.yasirkula.assetusagedetector",
|
||||||
"displayName": "Asset Usage Detector",
|
"displayName": "Asset Usage Detector",
|
||||||
"version": "1.9.0",
|
"version": "2.6.3",
|
||||||
"description": "This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!"
|
"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!"
|
||||||
}
|
}
|
||||||
|
|||||||