- Fixed cache issue that occurred after an asset was renamed

- Added an option to include non-serializable objects in search since some seemingly non-serializable Unity types are actually serialized with Unity magic (e.g. AnimatorControllerLayer)
- It is now possible to exclude some asset(s) and/or scene(s) from the search
- Added optional progressbar
This commit is contained in:
Süleyman Yasir KULA
2019-09-20 01:28:15 +03:00
parent 64eb175f8f
commit 0cd657456d
8 changed files with 691 additions and 384 deletions
Binary file not shown.
@@ -11,6 +11,7 @@ using System.Collections.Generic;
using System.Reflection;
using System;
using System.IO;
using UnityEngine.UI;
#if UNITY_2017_1_OR_NEWER
using UnityEngine.U2D;
#if UNITY_2018_2_OR_NEWER
@@ -39,11 +40,16 @@ namespace AssetUsageDetectorNamespace
public SceneSearchMode searchInScenes;
public bool searchInAssetsFolder;
public IEnumerable<Object> searchInAssetsSubset;
public IEnumerable<Object> excludedAssetsFromSearch;
public bool dontSearchInSourceAssets;
public IEnumerable<Object> excludedScenesFromSearch;
public int searchDepthLimit;
public BindingFlags fieldModifiers, propertyModifiers;
public bool searchNonSerializableVariables;
public bool noAssetDatabaseChanges;
public bool showProgressBar;
public Parameters()
{
@@ -51,10 +57,15 @@ namespace AssetUsageDetectorNamespace
searchInScenes = SceneSearchMode.AllScenes;
searchInAssetsFolder = true;
searchInAssetsSubset = null;
excludedAssetsFromSearch = null;
dontSearchInSourceAssets = false;
excludedScenesFromSearch = null;
searchDepthLimit = 4;
fieldModifiers = BindingFlags.Public | BindingFlags.NonPublic;
propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic;
searchNonSerializableVariables = true;
noAssetDatabaseChanges = false;
showProgressBar = false;
}
}
@@ -64,6 +75,7 @@ namespace AssetUsageDetectorNamespace
public string hash;
public string[] dependencies;
public long[] fileSizes;
public bool verified;
public Result searchResult;
@@ -73,10 +85,11 @@ namespace AssetUsageDetectorNamespace
Verify( path );
}
public CacheEntry( string hash, string[] dependencies )
public CacheEntry( string hash, string[] dependencies, long[] fileSizes )
{
this.hash = hash;
this.dependencies = dependencies;
this.fileSizes = fileSizes;
}
public void Verify( string path )
@@ -85,11 +98,21 @@ namespace AssetUsageDetectorNamespace
if( this.hash != hash )
{
this.hash = hash;
dependencies = AssetDatabase.GetDependencies( path, false );
Refresh( path );
}
verified = true;
}
public void Refresh( string path )
{
dependencies = AssetDatabase.GetDependencies( path, false );
if( fileSizes == null || fileSizes.Length != dependencies.Length )
fileSizes = new long[dependencies.Length];
for( int i = 0; i < dependencies.Length; i++ )
fileSizes[i] = new FileInfo( dependencies[i] ).Length;
}
}
#endregion
@@ -99,7 +122,7 @@ namespace AssetUsageDetectorNamespace
private HashSet<string> sceneObjectsToSearchScenesSet; // sceneObjectsToSearchSet's scene(s)
private HashSet<Object> assetsToSearchSet; // Project asset(s) in objectsToSearchSet
private HashSet<string> assetsToSearchPathsSet; // objectsToSearchSet's path(s)
private HashSet<string> assetsToSearchPathsSet; // assetsToSearchSet's path(s)
private SearchResultGroup currentSearchResultGroup; // Results for the currently searched scene
@@ -109,7 +132,7 @@ namespace AssetUsageDetectorNamespace
private Dictionary<Type, Func<Object, ReferenceNode>> typeToSearchFunction; // Dictionary to quickly find the function to search a specific type with
private Stack<object> callStack; // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
private List<object> callStack; // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
private bool searchPrefabConnections;
private bool searchMonoBehavioursForScript;
@@ -176,7 +199,7 @@ namespace AssetUsageDetectorNamespace
searchedObjects.Clear();
if( callStack == null )
callStack = new Stack<object>( 64 );
callStack = new List<object>( 64 );
else
callStack.Clear();
@@ -354,7 +377,7 @@ namespace AssetUsageDetectorNamespace
}
// By default, search only serializable variables for references
searchSerializableVariablesOnly = true;
searchSerializableVariablesOnly = !searchParameters.searchNonSerializableVariables;
// Initialize the nodes of searched asset(s)
foreach( Object obj in objectsToSearchSet )
@@ -367,6 +390,12 @@ namespace AssetUsageDetectorNamespace
searchedObjects[objHash] = PopReferenceNode( obj );
}
// Progressbar values
int searchProgress = 0;
int searchTotalProgress = scenesToSearch.Count;
if( EditorApplication.isPlaying )
searchTotalProgress++; // DontDestroyOnLoad scene
// Don't search assets if searched object(s) are all scene objects as assets can't hold references to scene objects
if( searchParameters.searchInAssetsFolder && assetsToSearchSet.Count > 0 )
{
@@ -375,27 +404,63 @@ namespace AssetUsageDetectorNamespace
// Get the paths of all assets that are to be searched
IEnumerable<string> assetPaths;
if( searchParameters.searchInAssetsSubset == null )
assetPaths = AssetDatabase.GetAllAssetPaths();
{
string[] allAssetPaths = AssetDatabase.GetAllAssetPaths();
searchTotalProgress += allAssetPaths.Length;
assetPaths = allAssetPaths;
}
else
{
folderContentsSet.Clear();
foreach( Object target in searchParameters.searchInAssetsSubset )
foreach( Object obj in searchParameters.searchInAssetsSubset )
{
if( target == null || target.Equals( null ) )
if( obj == null || obj.Equals( null ) )
continue;
if( target.IsFolder() )
folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( target ) );
if( !obj.IsAsset() )
continue;
if( obj.IsFolder() )
folderContentsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) );
else
folderContentsSet.Add( AssetDatabase.GetAssetPath( target ) );
folderContentsSet.Add( AssetDatabase.GetAssetPath( obj ) );
}
searchTotalProgress += folderContentsSet.Count;
assetPaths = folderContentsSet;
}
// Calculate the path(s) of the assets that won't be searched for references
HashSet<string> excludedAssetsPathsSet = new HashSet<string>();
if( searchParameters.excludedAssetsFromSearch != null )
{
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
{
if( obj == null || obj.Equals( null ) )
continue;
if( !obj.IsAsset() )
continue;
if( obj.IsFolder() )
excludedAssetsPathsSet.UnionWith( Utilities.EnumerateFolderContents( obj ) );
else
excludedAssetsPathsSet.Add( AssetDatabase.GetAssetPath( obj ) );
}
}
if( searchParameters.dontSearchInSourceAssets )
excludedAssetsPathsSet.UnionWith( assetsToSearchPathsSet );
foreach( string path in assetPaths )
{
if( searchParameters.showProgressBar && ++searchProgress % 30 == 1 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching assets", (float) searchProgress / searchTotalProgress ) )
throw new Exception( "Search aborted" );
if( excludedAssetsPathsSet.Contains( path ) )
continue;
// If asset resides inside the Assets directory and is not a scene asset
if( path.StartsWith( "Assets/" ) && !path.EndsWith( ".unity" ) )
{
@@ -426,16 +491,56 @@ namespace AssetUsageDetectorNamespace
if( EditorApplication.isPlaying )
searchSerializableVariablesOnly = false;
foreach( string scenePath in scenesToSearch )
if( scenesToSearch.Count > 0 )
{
// Search scene for references
if( !string.IsNullOrEmpty( scenePath ) )
// Calculate the path(s) of the scenes that won't be searched for references
HashSet<string> excludedScenesPathsSet = new HashSet<string>();
if( searchParameters.excludedScenesFromSearch != null )
{
foreach( Object obj in searchParameters.excludedScenesFromSearch )
{
if( obj == null || obj.Equals( null ) )
continue;
if( !obj.IsAsset() )
continue;
if( obj.IsFolder() )
{
string[] folderContents = AssetDatabase.FindAssets( "t:SceneAsset", new string[] { AssetDatabase.GetAssetPath( obj ) } );
if( folderContents == null )
continue;
for( int i = 0; i < folderContents.Length; i++ )
excludedScenesPathsSet.Add( AssetDatabase.GUIDToAssetPath( folderContents[i] ) );
}
else if( obj is SceneAsset )
excludedScenesPathsSet.Add( AssetDatabase.GetAssetPath( obj ) );
}
}
foreach( string scenePath in scenesToSearch )
{
if( searchParameters.showProgressBar && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: " + scenePath, (float) ++searchProgress / searchTotalProgress ) )
throw new Exception( "Search aborted" );
// Search scene for references
if( string.IsNullOrEmpty( scenePath ) )
continue;
if( excludedScenesPathsSet.Contains( scenePath ) )
continue;
SearchScene( scenePath, searchResult, initialSceneSetup );
}
}
// Search through all the GameObjects under the DontDestroyOnLoad scene (if exists)
if( EditorApplication.isPlaying )
{
if( searchParameters.showProgressBar && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Searching scene: DontDestroyOnLoad", 1f ) )
throw new Exception( "Search aborted" );
currentSearchResultGroup = new SearchResultGroup( "DontDestroyOnLoad", false );
GameObject[] rootGameObjects = GetDontDestroyOnLoadObjects();
@@ -470,19 +575,21 @@ namespace AssetUsageDetectorNamespace
{
currentSearchResultGroup = null;
currentObject = null;
EditorUtility.ClearProgressBar();
}
}
private void InitializeSearchResultNodes( List<SearchResultGroup> searchResult )
{
for( int i = 0; i < searchResult.Count; i++ )
searchResult[i].InitializeNodes();
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].NumberOfReferences == 0 )
searchResult.RemoveAt( i );
searchResult.RemoveAtFast( i );
}
}
@@ -520,17 +627,17 @@ namespace AssetUsageDetectorNamespace
{
// If searched asset is a GameObject, include its components in the search
Component[] components = ( (GameObject) obj ).GetComponents<Component>();
for( int j = 0; j < components.Length; j++ )
for( int i = 0; i < components.Length; i++ )
{
if( components[j] == null || components[j].Equals( null ) )
if( components[i] == null || components[i].Equals( null ) )
continue;
objectsToSearchSet.Add( components[j] );
objectsToSearchSet.Add( components[i] );
if( isAsset )
assetsToSearchSet.Add( components[j] );
assetsToSearchSet.Add( components[i] );
else
sceneObjectsToSearchSet.Add( components[j] );
sceneObjectsToSearchSet.Add( components[i] );
}
}
}
@@ -539,6 +646,8 @@ namespace AssetUsageDetectorNamespace
private void SearchScene( string scenePath, List<SearchResultGroup> searchResult, SceneSetup[] initialSceneSetup )
{
Scene scene = EditorSceneManager.GetSceneByPath( scenePath );
if( EditorApplication.isPlaying && !scene.isLoaded )
return;
bool canContainSceneObjectReference = scene.isLoaded && ( !EditorSceneManager.preventCrossSceneReferences || sceneObjectsToSearchScenesSet.Contains( scenePath ) );
if( !canContainSceneObjectReference )
@@ -617,7 +726,7 @@ namespace AssetUsageDetectorNamespace
return null;
// Avoid recursion (which leads to stackoverflow exception) using a stack
if( callStack.Contains( obj ) )
if( callStack.ContainsFast( obj ) )
return null;
// Hashing does not work well with structs all the time, don't cache search results for structs
@@ -660,7 +769,7 @@ namespace AssetUsageDetectorNamespace
return null;
}
callStack.Push( unityObject );
callStack.Add( unityObject );
// Search the Object in detail
Func<Object, ReferenceNode> func;
@@ -674,7 +783,7 @@ namespace AssetUsageDetectorNamespace
SearchFieldsAndPropertiesOf( result );
}
callStack.Pop();
callStack.RemoveAt( callStack.Count - 1 );
}
else
{
@@ -682,14 +791,14 @@ namespace AssetUsageDetectorNamespace
if( currentDepth >= searchDepthLimit )
return null;
callStack.Push( obj );
callStack.Add( obj );
currentDepth++;
result = PopReferenceNode( obj );
SearchFieldsAndPropertiesOf( result );
currentDepth--;
callStack.Pop();
callStack.RemoveAt( callStack.Count - 1 );
}
if( result != null && result.NumberOfOutgoingLinks == 0 )
@@ -755,8 +864,8 @@ namespace AssetUsageDetectorNamespace
// If an asset is a shader, texture or material, and this component is a Renderer,
// search it for references
Material[] materials = ( (Renderer) component ).sharedMaterials;
for( int j = 0; j < materials.Length; j++ )
referenceNode.AddLinkTo( SearchObject( materials[j] ) );
for( int i = 0; i < materials.Length; i++ )
referenceNode.AddLinkTo( SearchObject( materials[i] ) );
}
else if( component is Animation )
{
@@ -797,7 +906,6 @@ namespace AssetUsageDetectorNamespace
#endif
SearchFieldsAndPropertiesOf( referenceNode );
return referenceNode;
}
@@ -815,11 +923,11 @@ namespace AssetUsageDetectorNamespace
// Credit: http://answers.unity3d.com/answers/1116025/view.html
Shader shader = material.shader;
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
for( int k = 0; k < shaderPropertyCount; k++ )
for( int i = 0; i < shaderPropertyCount; i++ )
{
if( ShaderUtil.GetPropertyType( shader, k ) == ShaderUtil.ShaderPropertyType.TexEnv )
if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv )
{
string propertyName = ShaderUtil.GetPropertyName( shader, k );
string propertyName = ShaderUtil.GetPropertyName( shader, i );
Texture assignedTexture = material.GetTexture( propertyName );
if( objectsToSearchSet.Contains( assignedTexture ) )
referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName );
@@ -1025,6 +1133,8 @@ namespace AssetUsageDetectorNamespace
// 1- skip Obsolete variables
// 2- skip primitive types, enums and strings
// 3- skip common Unity types that can't hold any references (e.g. Vector3, Rect, Color, Quaternion)
//
// P.S. IsPrimitiveUnityType() extension function handles steps 2) and 3)
validVariables.Clear();
@@ -1045,6 +1155,13 @@ namespace AssetUsageDetectorNamespace
if( fields[i].FieldType.IsPrimitiveUnityType() )
continue;
// Additional filtering for fields:
// 1- Ignore "m_RectTransform", "m_CanvasRenderer" and "m_Canvas" fields of Graphic components
string fieldName = fields[i].Name;
if( typeof( Graphic ).IsAssignableFrom( currType ) &&
( fieldName == "m_RectTransform" || fieldName == "m_CanvasRenderer" || fieldName == "m_Canvas" ) )
continue;
VariableGetVal getter = fields[i].CreateGetter( type );
if( getter != null )
validVariables.Add( new VariableGetterHolder( fields[i], getter, fields[i].IsSerializable() ) );
@@ -1070,33 +1187,39 @@ namespace AssetUsageDetectorNamespace
if( properties[i].PropertyType.IsPrimitiveUnityType() )
continue;
// No need to check properties with 'override' keyword
if( properties[i].IsOverridden() )
continue;
// Additional filtering for properties:
// 1- Ignore "gameObject", "transform", "rectTransform" and "attachedRigidbody" properties of Component's to get more useful results
// 2- Ignore "canvasRenderer" and "canvas" properties of Graphic components
// 3 & 4- Prevent accessing properties of Unity that instantiate an existing resource (causing leak)
// 3 & 4- Prevent accessing properties of Unity that instantiate an existing resource (causing memory leak)
string propertyName = properties[i].Name;
if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName.Equals( "gameObject" ) ||
propertyName.Equals( "transform" ) || propertyName.Equals( "attachedRigidbody" ) || propertyName.Equals( "rectTransform" ) ) )
if( typeof( Component ).IsAssignableFrom( currType ) && ( propertyName == "gameObject" ||
propertyName == "transform" || propertyName == "attachedRigidbody" || propertyName == "rectTransform" ) )
continue;
else if( typeof( UnityEngine.UI.Graphic ).IsAssignableFrom( currType ) &&
( propertyName.Equals( "canvasRenderer" ) || propertyName.Equals( "canvas" ) ) )
else if( typeof( Graphic ).IsAssignableFrom( currType ) &&
( propertyName == "canvasRenderer" || propertyName == "canvas" ) )
continue;
else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName.Equals( "mesh" ) )
else if( typeof( MeshFilter ).IsAssignableFrom( currType ) && propertyName == "mesh" )
continue;
else if( typeof( Renderer ).IsAssignableFrom( currType ) &&
( propertyName.Equals( "sharedMaterial" ) || propertyName.Equals( "sharedMaterials" ) ) )
( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) )
continue;
else if( ( propertyName.Equals( "material" ) || propertyName.Equals( "materials" ) ) &&
else if( ( propertyName == "material" || propertyName == "materials" ) &&
( typeof( Renderer ).IsAssignableFrom( currType ) || typeof( Collider ).IsAssignableFrom( currType ) ||
typeof( Collider2D ).IsAssignableFrom( currType )
#if !UNITY_2019_3_OR_NEWER
#pragma warning disable 0618
|| typeof( GUIText ).IsAssignableFrom( currType ) ) )
#pragma warning restore 0618
#endif
continue;
else
{
VariableGetVal getter = properties[i].CreateGetter();
if( getter != null && !properties[i].IsOverridden() ) // No need to check properties with 'override' keyword
if( getter != null )
validVariables.Add( new VariableGetterHolder( properties[i], getter, properties[i].IsSerializable() ) );
}
}
@@ -1131,8 +1254,20 @@ namespace AssetUsageDetectorNamespace
cacheEntry.searchResult = CacheEntry.Result.No;
string[] dependencies = cacheEntry.dependencies;
long[] fileSizes = cacheEntry.fileSizes;
for( int i = 0; i < dependencies.Length; i++ )
{
// If a dependency was renamed (which doesn't affect the verified hash, unfortunately),
// force refresh the asset's dependencies and search it again
FileInfo assetFile = new FileInfo( dependencies[i] );
if( !assetFile.Exists || assetFile.Length != fileSizes[i] )
{
cacheEntry.Refresh( assetPath );
cacheEntry.searchResult = CacheEntry.Result.Unknown;
return AssetHasAnyReference( assetPath );
}
if( assetsToSearchPathsSet.Contains( dependencies[i] ) )
{
cacheEntry.searchResult = CacheEntry.Result.Yes;
@@ -1153,12 +1288,10 @@ namespace AssetUsageDetectorNamespace
}
// Get reference node for object
private ReferenceNode GetReferenceNode( object nodeObject, string hash = null )
private ReferenceNode GetReferenceNode( object nodeObject )
{
if( hash == null )
hash = nodeObject.Hash();
ReferenceNode result;
string hash = nodeObject.Hash();
if( !searchedObjects.TryGetValue( hash, out result ) || result == null )
{
result = PopReferenceNode( nodeObject );
@@ -1229,13 +1362,17 @@ namespace AssetUsageDetectorNamespace
{
CacheEntry cacheEntry = keyValuePair.Value;
string[] dependencies = cacheEntry.dependencies;
long[] fileSizes = cacheEntry.fileSizes;
writer.Write( keyValuePair.Key );
writer.Write( cacheEntry.hash );
writer.Write( dependencies.Length );
for( int i = 0; i < dependencies.Length; i++ )
{
writer.Write( dependencies[i] );
writer.Write( fileSizes[i] );
}
}
}
}
@@ -1264,10 +1401,14 @@ namespace AssetUsageDetectorNamespace
int dependenciesLength = reader.ReadInt32();
string[] dependencies = new string[dependenciesLength];
long[] fileSizes = new long[dependenciesLength];
for( int j = 0; j < dependenciesLength; j++ )
{
dependencies[j] = reader.ReadString();
fileSizes[j] = reader.ReadInt64();
}
assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies );
assetDependencyCache[assetPath] = new CacheEntry( hash, dependencies, fileSizes );
}
}
catch( Exception e )
@@ -1286,23 +1427,34 @@ namespace AssetUsageDetectorNamespace
string[] allAssets = AssetDatabase.GetAllAssetPaths();
if( allAssets.Length > 0 )
{
string title = "Please wait...";
string message = "Generating cache for the first time";
double startTime = EditorApplication.timeSinceStartup;
EditorUtility.DisplayProgressBar( title, message, 0f );
for( int i = 0; i < allAssets.Length; i++ )
try
{
AssetHasAnyReference( allAssets[i] );
EditorUtility.DisplayProgressBar( title, message, (float) i / allAssets.Length );
for( int i = 0; i < allAssets.Length; i++ )
{
if( i % 30 == 0 && EditorUtility.DisplayCancelableProgressBar( "Please wait...", "Generating cache for the first time", (float) i / allAssets.Length ) )
{
EditorUtility.ClearProgressBar();
Debug.LogWarning( "Initial cache generation cancelled, cache will be generated on the fly as more and more assets are searched." );
break;
}
AssetHasAnyReference( allAssets[i] );
}
EditorUtility.ClearProgressBar();
Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" );
Debug.Log( "You can always reset the cache by deleting " + Path.GetFullPath( CachePath ) );
SaveCache();
}
catch( Exception e )
{
EditorUtility.ClearProgressBar();
Debug.LogException( e );
}
EditorUtility.ClearProgressBar();
Debug.Log( "Cache generated in " + ( EditorApplication.timeSinceStartup - startTime ).ToString( "F2" ) + " seconds" );
SaveCache();
}
}
}
@@ -16,10 +16,13 @@ namespace AssetUsageDetectorNamespace.Extras
private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties";
private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
private const string PREFS_PATH_DRAWING_MODE = "AUD_PathDrawing";
private const string PREFS_SHOW_PROGRESS = "AUD_Progress";
private const string PREFS_SHOW_TOOLTIPS = "AUD_Tooltips";
private AssetUsageDetector core = new AssetUsageDetector();
@@ -34,15 +37,21 @@ namespace AssetUsageDetectorNamespace.Extras
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
private bool searchInAssetsFolder = true; // Assets in Project view
private bool dontSearchInSourceAssets = false; // objectsToSearch won't be searched for internal references
private List<Object> searchInAssetsSubset = new List<Object>() { null }; // If not empty, only these assets are searched for references
private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
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 restoreInitialSceneSetup = true; // Close the additively loaded scenes that were not part of the initial scene setup
private string errorMessage = string.Empty;
private bool searchNonSerializableVariables = true;
private bool noAssetDatabaseChanges = false;
private bool showProgressBar = false;
private BindingFlags fieldModifiers, propertyModifiers;
@@ -50,6 +59,11 @@ namespace AssetUsageDetectorNamespace.Extras
private double nextPlayModeRefreshTime = 0f;
private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );
private Vector2 scrollPosition = Vector2.zero;
private static AssetUsageDetectorWindow visibleWindow = null;
@@ -83,7 +97,7 @@ namespace AssetUsageDetectorNamespace.Extras
// Quickly show the AssetUsageDetector window and initiate a search
public static void ShowAndSearch( IEnumerable<Object> searchObjects )
{
ShowAndSearch( new AssetUsageDetector.Parameters() { objectsToSearch = searchObjects } );
ShowAndSearchInternal( searchObjects, null );
}
// Quickly show the AssetUsageDetector window and initiate a search
@@ -95,44 +109,61 @@ namespace AssetUsageDetectorNamespace.Extras
return;
}
if( searchParameters.objectsToSearch.IsEmpty() )
ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters );
}
private static void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters )
{
if( visibleWindow != null && !visibleWindow.ReturnToSetupPhase( true ) )
{
Debug.LogError( "searchParameters.objectsToSearch can't be empty!" );
Debug.LogError( "Need to reset the previous search first!" );
return;
}
if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
{
if( visibleWindow == null || visibleWindow.currentPhase != Phase.Complete )
{
Debug.LogError( "Save open scenes first!" );
return;
}
if( !visibleWindow.ReturnToSetupPhase( true ) )
{
Debug.LogError( "Need to reset the previous search first!" );
return;
}
}
Init();
if( visibleWindow.objectsToSearch == null )
visibleWindow.objectsToSearch = new List<ObjectToSearch>();
else
visibleWindow.objectsToSearch.Clear();
visibleWindow.objectsToSearch.Clear();
if( searchObjects != null )
{
foreach( Object obj in searchObjects )
visibleWindow.objectsToSearch.Add( new ObjectToSearch( obj ) );
}
foreach( Object obj in searchParameters.objectsToSearch )
visibleWindow.objectsToSearch.Add( new ObjectToSearch( obj ) );
if( searchParameters != null )
{
visibleWindow.ParseSceneSearchMode( searchParameters.searchInScenes );
visibleWindow.searchInAssetsFolder = searchParameters.searchInAssetsFolder;
visibleWindow.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
visibleWindow.searchDepthLimit = searchParameters.searchDepthLimit;
visibleWindow.fieldModifiers = searchParameters.fieldModifiers;
visibleWindow.propertyModifiers = searchParameters.propertyModifiers;
visibleWindow.searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
visibleWindow.noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
visibleWindow.showProgressBar = searchParameters.showProgressBar;
// This enumerator includes sub-assets in the search
searchParameters.objectsToSearch = new ObjectToSearchEnumerator( visibleWindow.objectsToSearch );
visibleWindow.searchInAssetsSubset.Clear();
if( searchParameters.searchInAssetsSubset != null )
{
foreach( Object obj in searchParameters.searchInAssetsSubset )
visibleWindow.searchInAssetsSubset.Add( obj );
}
visibleWindow.errorMessage = string.Empty;
visibleWindow.currentPhase = Phase.Processing;
visibleWindow.searchResult = visibleWindow.core.Run( searchParameters );
visibleWindow.currentPhase = Phase.Complete;
visibleWindow.excludedAssets.Clear();
if( searchParameters.excludedAssetsFromSearch != null )
{
foreach( Object obj in searchParameters.excludedAssetsFromSearch )
visibleWindow.excludedAssets.Add( obj );
}
visibleWindow.excludedScenes.Clear();
if( searchParameters.excludedScenesFromSearch != null )
{
foreach( Object obj in searchParameters.excludedScenesFromSearch )
visibleWindow.excludedScenes.Add( obj );
}
}
visibleWindow.InitiateSearch();
}
private void OnEnable()
@@ -158,32 +189,24 @@ namespace AssetUsageDetectorNamespace.Extras
private void SavePrefs()
{
SceneSearchMode sceneSearchMode = SceneSearchMode.None;
if( searchInOpenScenes )
sceneSearchMode |= SceneSearchMode.OpenScenes;
if( searchInScenesInBuild )
sceneSearchMode |= searchInScenesInBuildTickedOnly ? SceneSearchMode.ScenesInBuildSettingsTickedOnly : SceneSearchMode.ScenesInBuildSettingsAll;
if( searchInAllScenes )
sceneSearchMode |= SceneSearchMode.AllScenes;
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) sceneSearchMode );
EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
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_SHOW_TOOLTIPS, searchResultDrawParameters.showTooltips );
EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showProgressBar );
}
private void LoadPrefs()
{
SceneSearchMode sceneSearchMode = (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) );
searchInOpenScenes = ( sceneSearchMode & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes;
searchInScenesInBuild = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll || ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly;
searchInScenesInBuildTickedOnly = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) != SceneSearchMode.ScenesInBuildSettingsAll;
searchInAllScenes = ( sceneSearchMode & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes;
ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );
searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, false );
searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
// Fetch public, protected and private non-static fields and properties from objects by default
@@ -199,7 +222,33 @@ namespace AssetUsageDetectorNamespace.Extras
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
}
searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
searchResultDrawParameters.showTooltips = EditorPrefs.GetBool( PREFS_SHOW_TOOLTIPS, false );
showProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, false );
}
private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
{
SceneSearchMode sceneSearchMode = SceneSearchMode.None;
if( searchInOpenScenes )
sceneSearchMode |= SceneSearchMode.OpenScenes;
if( !hideOptionsInPlayMode || !EditorApplication.isPlaying )
{
if( searchInScenesInBuild )
sceneSearchMode |= searchInScenesInBuildTickedOnly ? SceneSearchMode.ScenesInBuildSettingsTickedOnly : SceneSearchMode.ScenesInBuildSettingsAll;
if( searchInAllScenes )
sceneSearchMode |= SceneSearchMode.AllScenes;
}
return sceneSearchMode;
}
private void ParseSceneSearchMode( SceneSearchMode sceneSearchMode )
{
searchInOpenScenes = ( sceneSearchMode & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes;
searchInScenesInBuild = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll || ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly;
searchInScenesInBuildTickedOnly = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) != SceneSearchMode.ScenesInBuildSettingsAll;
searchInAllScenes = ( sceneSearchMode & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes;
}
private void Update()
@@ -239,7 +288,7 @@ namespace AssetUsageDetectorNamespace.Extras
}
else if( currentPhase == Phase.Setup )
{
if( ExposeSearchedObjects() )
if( objectsToSearchDrawer.Draw( objectsToSearch ) )
errorMessage = string.Empty;
GUILayout.Space( 10 );
@@ -254,7 +303,10 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 35 );
GUILayout.BeginVertical();
ExposeAssetsToSearch();
searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
excludedAssetsDrawer.Draw( excludedAssets );
dontSearchInSourceAssets = EditorGUILayout.ToggleLeft( "Don't search 'Asset(s)' themselves for references", dontSearchInSourceAssets );
GUILayout.EndVertical();
GUILayout.EndHorizontal();
@@ -262,38 +314,39 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 10 );
if( EditorApplication.isPlaying )
{
searchInAllScenes = false;
searchInScenesInBuild = false;
}
else if( searchInAllScenes )
if( searchInAllScenes && !EditorApplication.isPlaying )
GUI.enabled = false;
searchInOpenScenes = EditorGUILayout.ToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes );
if( EditorApplication.isPlaying )
GUI.enabled = false;
searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", searchInScenesInBuild );
if( searchInScenesInBuild )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
GUILayout.EndHorizontal();
}
if( !EditorApplication.isPlaying )
{
searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", true );
if( searchInScenesInBuild )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
GUILayout.EndHorizontal();
}
GUI.enabled = true;
searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes );
searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes );
}
GUI.enabled = true;
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
GUILayout.BeginVertical();
excludedScenesDrawer.Draw( excludedScenes );
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.Space( 10 );
@@ -325,7 +378,7 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.EndHorizontal();
GUILayout.Label( "> Search properties (can be slow):" );
GUILayout.Label( "> Search properties:" );
GUILayout.BeginHorizontal();
@@ -345,66 +398,23 @@ namespace AssetUsageDetectorNamespace.Extras
GUILayout.Space( 10 );
searchNonSerializableVariables = EditorGUILayout.ToggleLeft( "Include non-serializable fields and properties in search (slower search)", searchNonSerializableVariables );
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
showProgressBar = EditorGUILayout.ToggleLeft( "Show progress bar (slower search)", showProgressBar );
// Don't let the user press the GO button without any valid search location
if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder )
GUI.enabled = false;
noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) )
{
if( objectsToSearch.IsEmpty() )
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;
SceneSearchMode sceneSearchMode = SceneSearchMode.None;
if( searchInAllScenes )
sceneSearchMode = SceneSearchMode.AllScenes;
else
{
if( searchInOpenScenes )
sceneSearchMode = SceneSearchMode.OpenScenes;
if( searchInScenesInBuild )
{
if( searchInScenesInBuildTickedOnly )
sceneSearchMode |= SceneSearchMode.ScenesInBuildSettingsTickedOnly;
else
sceneSearchMode |= SceneSearchMode.ScenesInBuildSettingsAll;
}
}
// Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ) : null,
searchInScenes = sceneSearchMode,
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset : null,
fieldModifiers = fieldModifiers,
propertyModifiers = propertyModifiers,
searchDepthLimit = searchDepthLimit,
noAssetDatabaseChanges = noAssetDatabaseChanges
} );
currentPhase = Phase.Complete;
}
}
InitiateSearch();
}
else if( currentPhase == Phase.Complete )
{
// Draw the results of the search
GUI.enabled = false;
ExposeSearchedObjects();
objectsToSearchDrawer.Draw( objectsToSearch );
GUILayout.Space( 10 );
GUI.enabled = true;
@@ -499,191 +509,41 @@ namespace AssetUsageDetectorNamespace.Extras
EditorGUILayout.EndScrollView();
}
// Exposes objectsToSearch as an array field on GUI
private bool ExposeSearchedObjects()
private void InitiateSearch()
{
bool hasChanged = false;
bool guiEnabled = GUI.enabled;
Event ev = Event.current;
GUILayout.BeginHorizontal();
GUILayout.Label( "Asset(s):" );
if( guiEnabled )
if( objectsToSearch.IsEmpty() )
errorMessage = "ADD AN ASSET TO THE LIST FIRST!";
else if( !EditorApplication.isPlaying && !Utilities.AreScenesSaved() )
{
// Handle drag & drop references to array
// Credit: https://answers.unity.com/answers/657877/view.html
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) &&
GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if( ev.type == EventType.DragPerform )
{
DragAndDrop.AcceptDrag();
Object[] draggedObjects = DragAndDrop.objectReferences;
if( draggedObjects.Length > 0 )
{
for( int i = 0; i < draggedObjects.Length; i++ )
{
if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) )
{
hasChanged = true;
objectsToSearch.Add( new ObjectToSearch( draggedObjects[i] ) );
}
}
}
}
ev.Use();
}
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
objectsToSearch.Insert( 0, new ObjectToSearch( null ) );
// Don't start the search if at least one scene is currently dirty (not saved)
errorMessage = "SAVE OPEN SCENES FIRST!";
}
GUILayout.EndHorizontal();
for( int i = 0; i < objectsToSearch.Count; i++ )
else
{
ObjectToSearch objToSearch = objectsToSearch[i];
errorMessage = string.Empty;
currentPhase = Phase.Processing;
GUI.changed = false;
GUILayout.BeginHorizontal();
SavePrefs();
Object prevAssetToSearch = objToSearch.obj;
objToSearch.obj = EditorGUILayout.ObjectField( "", objToSearch.obj, typeof( Object ), true );
if( GUI.changed && prevAssetToSearch != objToSearch.obj )
// Start searching
searchResult = core.Run( new AssetUsageDetector.Parameters()
{
hasChanged = true;
objToSearch.RefreshSubAssets();
}
objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ) : null,
searchInScenes = GetSceneSearchMode( true ),
searchInAssetsFolder = searchInAssetsFolder,
searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset : null,
excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets : null,
dontSearchInSourceAssets = dontSearchInSourceAssets,
excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes : null,
fieldModifiers = fieldModifiers,
propertyModifiers = propertyModifiers,
searchDepthLimit = searchDepthLimit,
searchNonSerializableVariables = searchNonSerializableVariables,
noAssetDatabaseChanges = noAssetDatabaseChanges,
showProgressBar = showProgressBar
} );
if( guiEnabled )
{
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
objectsToSearch.Insert( i + 1, new ObjectToSearch( null ) );
if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) )
{
if( objToSearch != null && !objToSearch.Equals( null ) )
hasChanged = true;
objectsToSearch.RemoveAt( i-- );
}
}
GUILayout.EndHorizontal();
List<ObjectToSearch.SubAsset> subAssetsToSearch = objToSearch.subAssets;
if( subAssetsToSearch.Count > 0 )
{
GUILayout.BeginHorizontal();
// 0-> all toggles off, 1-> mixed, 2-> all toggles on
bool toggleAllSubAssets = subAssetsToSearch[0].shouldSearch;
bool mixedToggle = false;
for( int j = 1; j < subAssetsToSearch.Count; j++ )
{
if( subAssetsToSearch[j].shouldSearch != toggleAllSubAssets )
{
mixedToggle = true;
break;
}
}
if( mixedToggle )
EditorGUI.showMixedValue = true;
GUI.changed = false;
toggleAllSubAssets = EditorGUILayout.Toggle( toggleAllSubAssets, Utilities.GL_WIDTH_25 );
if( GUI.changed )
{
for( int j = 0; j < subAssetsToSearch.Count; j++ )
subAssetsToSearch[j].shouldSearch = toggleAllSubAssets;
}
EditorGUI.showMixedValue = false;
objToSearch.showSubAssetsFoldout = EditorGUILayout.Foldout( objToSearch.showSubAssetsFoldout, "Include sub-assets in search:", true );
GUILayout.EndHorizontal();
if( objToSearch.showSubAssetsFoldout )
{
for( int j = 0; j < subAssetsToSearch.Count; j++ )
{
GUILayout.BeginHorizontal();
subAssetsToSearch[j].shouldSearch = EditorGUILayout.Toggle( subAssetsToSearch[j].shouldSearch, Utilities.GL_WIDTH_25 );
GUI.enabled = false;
EditorGUILayout.ObjectField( string.Empty, subAssetsToSearch[j].subAsset, typeof( Object ), true );
GUI.enabled = guiEnabled;
GUILayout.EndHorizontal();
}
}
}
}
return hasChanged;
}
// Exposes searchInAssetsSubset as an array field on GUI
private void ExposeAssetsToSearch()
{
Event ev = Event.current;
GUILayout.BeginHorizontal();
GUILayout.Label( "Search in following asset(s) only:" );
// Handle drag & drop references to array
// Credit: https://answers.unity.com/answers/657877/view.html
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) &&
GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if( ev.type == EventType.DragPerform )
{
DragAndDrop.AcceptDrag();
Object[] draggedObjects = DragAndDrop.objectReferences;
if( draggedObjects.Length > 0 )
{
for( int i = 0; i < draggedObjects.Length; i++ )
{
if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) )
searchInAssetsSubset.Add( draggedObjects[i] );
}
}
}
ev.Use();
}
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
searchInAssetsSubset.Insert( 0, null );
GUILayout.EndHorizontal();
for( int i = 0; i < searchInAssetsSubset.Count; i++ )
{
GUILayout.BeginHorizontal();
searchInAssetsSubset[i] = EditorGUILayout.ObjectField( "", searchInAssetsSubset[i], typeof( Object ), false );
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
searchInAssetsSubset.Insert( i + 1, null );
if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) )
searchInAssetsSubset.RemoveAt( i-- );
GUILayout.EndHorizontal();
currentPhase = Phase.Complete;
}
}
@@ -0,0 +1,216 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AssetUsageDetectorNamespace.Extras
{
public abstract class ListDrawer<T>
{
private readonly string label;
private readonly bool acceptSceneObjects;
protected ListDrawer( string label, bool acceptSceneObjects )
{
this.label = label;
this.acceptSceneObjects = acceptSceneObjects;
}
// Exposes a list on GUI
public bool Draw( List<T> list )
{
bool hasChanged = false;
bool guiEnabled = GUI.enabled;
Event ev = Event.current;
GUILayout.BeginHorizontal();
GUILayout.Label( label );
if( guiEnabled )
{
// Handle drag & drop references to array
// Credit: https://answers.unity.com/answers/657877/view.html
if( ( ev.type == EventType.DragPerform || ev.type == EventType.DragUpdated ) &&
GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if( ev.type == EventType.DragPerform )
{
DragAndDrop.AcceptDrag();
Object[] draggedObjects = DragAndDrop.objectReferences;
if( draggedObjects.Length > 0 )
{
for( int i = 0; i < draggedObjects.Length; i++ )
{
if( draggedObjects[i] != null && !draggedObjects[i].Equals( null ) )
{
hasChanged = true;
list.Add( CreateElement( draggedObjects[i] ) );
}
}
}
}
ev.Use();
}
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
list.Insert( 0, CreateElement( null ) );
}
GUILayout.EndHorizontal();
for( int i = 0; i < list.Count; i++ )
{
T element = list[i];
GUI.changed = false;
GUILayout.BeginHorizontal();
Object prevObject = GetObjectFromElement( element );
Object newObject = EditorGUILayout.ObjectField( "", prevObject, typeof( Object ), acceptSceneObjects );
if( GUI.changed && prevObject != newObject )
{
hasChanged = true;
SetObjectOfElement( list, i, newObject );
}
if( guiEnabled )
{
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
list.Insert( i + 1, CreateElement( null ) );
if( GUILayout.Button( "-", Utilities.GL_WIDTH_25 ) )
{
if( element != null && !element.Equals( null ) )
hasChanged = true;
// Lists with no elements look ugly, always keep a dummy null variable
if( list.Count > 1 )
list.RemoveAt( i-- );
else
list[0] = CreateElement( null );
}
}
GUILayout.EndHorizontal();
PostElementDrawer( element );
}
return hasChanged;
}
protected abstract T CreateElement( Object source );
protected abstract Object GetObjectFromElement( T element );
protected abstract void SetObjectOfElement( List<T> list, int index, Object value );
protected abstract void PostElementDrawer( T element );
}
public class ObjectListDrawer : ListDrawer<Object>
{
public ObjectListDrawer( string label, bool acceptSceneObjects ) : base( label, acceptSceneObjects )
{
}
protected override Object CreateElement( Object source )
{
return source;
}
protected override Object GetObjectFromElement( Object element )
{
return element;
}
protected override void SetObjectOfElement( List<Object> list, int index, Object value )
{
list[index] = value;
}
protected override void PostElementDrawer( Object element )
{
}
}
public class ObjectToSearchListDrawer : ListDrawer<ObjectToSearch>
{
public ObjectToSearchListDrawer() : base( "Asset(s):", true )
{
}
protected override ObjectToSearch CreateElement( Object source )
{
return new ObjectToSearch( source );
}
protected override Object GetObjectFromElement( ObjectToSearch element )
{
return element.obj;
}
protected override void SetObjectOfElement( List<ObjectToSearch> list, int index, Object value )
{
list[index].obj = value;
list[index].RefreshSubAssets();
}
protected override void PostElementDrawer( ObjectToSearch element )
{
List<ObjectToSearch.SubAsset> subAssetsToSearch = element.subAssets;
if( subAssetsToSearch.Count > 0 )
{
GUILayout.BeginHorizontal();
// 0-> all toggles off, 1-> mixed, 2-> all toggles on
bool toggleAllSubAssets = subAssetsToSearch[0].shouldSearch;
bool mixedToggle = false;
for( int j = 1; j < subAssetsToSearch.Count; j++ )
{
if( subAssetsToSearch[j].shouldSearch != toggleAllSubAssets )
{
mixedToggle = true;
break;
}
}
if( mixedToggle )
EditorGUI.showMixedValue = true;
GUI.changed = false;
toggleAllSubAssets = EditorGUILayout.Toggle( toggleAllSubAssets, Utilities.GL_WIDTH_25 );
if( GUI.changed )
{
for( int j = 0; j < subAssetsToSearch.Count; j++ )
subAssetsToSearch[j].shouldSearch = toggleAllSubAssets;
}
EditorGUI.showMixedValue = false;
element.showSubAssetsFoldout = EditorGUILayout.Foldout( element.showSubAssetsFoldout, "Include sub-assets in search:", true );
GUILayout.EndHorizontal();
if( element.showSubAssetsFoldout )
{
for( int j = 0; j < subAssetsToSearch.Count; j++ )
{
GUILayout.BeginHorizontal();
subAssetsToSearch[j].shouldSearch = EditorGUILayout.Toggle( subAssetsToSearch[j].shouldSearch, Utilities.GL_WIDTH_25 );
bool guiEnabled = GUI.enabled;
GUI.enabled = false;
EditorGUILayout.ObjectField( string.Empty, subAssetsToSearch[j].subAsset, typeof( Object ), true );
GUI.enabled = guiEnabled;
GUILayout.EndHorizontal();
}
}
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 88a4a4e861026b2498a437ce1e12b054
timeCreated: 1568758673
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -58,7 +58,7 @@ namespace AssetUsageDetectorNamespace
public SearchResultGroup this[int index] { get { return result[index]; } }
public bool SearchCompletedSuccessfully { get { return success; } }
public bool InitialSceneSetupConfigured { get { return initialSceneSetup != null; } }
public bool InitialSceneSetupConfigured { get { return initialSceneSetup != null && initialSceneSetup.Length > 0; } }
public SearchResult( bool success, List<SearchResultGroup> result, SceneSetup[] initialSceneSetup )
{
@@ -158,7 +158,7 @@ namespace AssetUsageDetectorNamespace
// Returns true if initial scene setup is restored successfully
public bool RestoreInitialSceneSetup()
{
if( initialSceneSetup == null )
if( initialSceneSetup == null || initialSceneSetup.Length == 0 )
return true;
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
@@ -284,36 +284,58 @@ namespace AssetUsageDetectorNamespace
}
// Initializes commonly used variables of the nodes
public void InitializeNodes()
public void InitializeNodes( Func<object, ReferenceNode> nodeGetter )
{
// Remove root nodes that don't have any outgoing links or have null node objects (somehow)
for( int i = references.Count - 1; i >= 0; i-- )
{
ReferenceNode node = references[i];
if( node.NumberOfOutgoingLinks == 0 )
references.RemoveAt( i );
if( references[i].NumberOfOutgoingLinks == 0 )
references.RemoveAtFast( i );
else
{
// For simplicity's sake, get rid of root nodes that are
// already part of another node's hierarchy
bool isRootNodeChildOfOtherNode = false;
for( int j = references.Count - 1; j >= 0; j-- )
{
if( i == j )
continue;
if( references[j].NodeExistsInChildrenRecursive( node ) )
{
isRootNodeChildOfOtherNode = true;
break;
}
}
if( isRootNodeChildOfOtherNode )
references.RemoveAt( i );
else
node.InitializeRecursively();
object nodeObject = references[i].nodeObject;
if( nodeObject == null || nodeObject.Equals( null ) )
references.RemoveAtFast( i );
}
}
// For simplicity's sake, get rid of root nodes that are already part of another node's hierarchy
for( int i = references.Count - 1; i >= 0; i-- )
{
if( IsRootNodePartOfAnotherRootNode( i ) )
references.RemoveAtFast( i );
}
// For clarity, a reference path shouldn't start with a sub-asset but instead with its corresponding main asset
for( int i = references.Count - 1; i >= 0; i-- )
{
object nodeObject = references[i].nodeObject;
if( nodeObject.IsAsset() && !AssetDatabase.IsMainAsset( (Object) nodeObject ) )
{
string assetPath = AssetDatabase.GetAssetPath( (Object) nodeObject );
if( string.IsNullOrEmpty( assetPath ) )
continue;
Object mainAsset = AssetDatabase.LoadMainAssetAtPath( assetPath );
if( mainAsset == null || mainAsset.Equals( null ) )
continue;
if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset )
continue;
// Get a ReferenceNode for the main asset, add a link to the sub-asset's node and change the root node
ReferenceNode newRootNode = nodeGetter( mainAsset );
newRootNode.AddLinkTo( references[i], ( nodeObject is Component || nodeObject is GameObject ) ? "Child object" : "Sub-asset" );
references[i] = newRootNode;
// Make sure that the new root node isn't already a part of another node's hierarchy
if( IsRootNodePartOfAnotherRootNode( i ) )
references.RemoveAtFast( i );
}
}
for( int i = references.Count - 1; i >= 0; i-- )
references[i].InitializeRecursively();
}
// Check if node exists in this results set
@@ -328,6 +350,21 @@ namespace AssetUsageDetectorNamespace
return false;
}
private bool IsRootNodePartOfAnotherRootNode( int index )
{
ReferenceNode node = references[index];
for( int i = references.Count - 1; i >= 0; i-- )
{
if( index == i )
continue;
if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node ) )
return true;
}
return false;
}
// Add all the Object's in this container to the set
public void AddObjectsTo( HashSet<Object> objectsSet )
{
@@ -533,7 +570,7 @@ namespace AssetUsageDetectorNamespace
// Add a one-way connection to another node
public void AddLinkTo( ReferenceNode nextNode, string description = null )
{
if( nextNode != null )
if( nextNode != null && nextNode != this )
{
if( !string.IsNullOrEmpty( description ) )
description = "[" + description + "]";
@@ -418,5 +418,35 @@ namespace AssetUsageDetectorNamespace.Extras
return true;
}
public static bool ContainsFast<T>( this List<T> list, T element )
{
if( !( element is ValueType ) )
{
for( int i = list.Count - 1; i >= 0; i-- )
{
if( ReferenceEquals( list[i], element ) )
return true;
}
}
else
{
for( int i = list.Count - 1; i >= 0; i-- )
{
if( element.Equals( list[i] ) )
return true;
}
}
return false;
}
public static void RemoveAtFast<T>( this List<T> list, int index )
{
int lastElementIndex = list.Count - 1;
list[index] = list[lastElementIndex];
list.RemoveAt( lastElementIndex );
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ This editor extension helps you figure out at which places an asset or GameObjec
### B. HOW TO USE
- Import **AssetUsageDetector.unitypackage** to your project
- Import [AssetUsageDetector.unitypackage](https://github.com/yasirkula/UnityAssetUsageDetector/releases) to your project
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- or, use the **Assets - Search For References** shortcut to find the selected object(s)' references