- Made AssetUsageDetector a standalone editor script, so you can now use it in your own editor scripts to calculate some objects' references

- Separated more classes into different scripts
This commit is contained in:
Süleyman Yasir KULA
2019-07-02 19:43:40 +03:00
parent b804967674
commit 50820f7cb6
9 changed files with 1286 additions and 943 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,584 @@
// Asset Usage Detector - by Suleyman Yasir KULA (yasirkula@gmail.com)
using UnityEngine;
using UnityEditor;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
public enum Phase { Setup, Processing, Complete };
public enum PathDrawingMode { Full, ShortRelevantParts, Shortest };
public class AssetUsageDetectorWindow : EditorWindow
{
private const float PLAY_MODE_REFRESH_INTERVAL = 1f; // Interval to refresh the editor window in play mode
private AssetUsageDetector core = new AssetUsageDetector();
private SearchResult searchResult; // Overall search results
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
private Phase currentPhase = Phase.Setup;
private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view
private bool searchInScenesInBuild = true; // Scenes in build
private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
private bool searchInAssetsFolder = true; // Assets in Project view
private List<Object> searchInAssetsSubset = new List<Object>() { null }; // If not empty, only these assets are 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 noAssetDatabaseChanges = false;
// Fetch public, protected and private non-static fields and properties from objects by default
private BindingFlags fieldModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic;
private BindingFlags propertyModifiers = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic;
private SearchResultDrawParameters searchResultDrawParameters = new SearchResultDrawParameters( PathDrawingMode.ShortRelevantParts, false );
private double nextPlayModeRefreshTime = 0f;
private Vector2 scrollPosition = Vector2.zero;
// Add "Asset Usage Detector" menu item to the Window menu
[MenuItem( "Window/Asset Usage Detector" )]
private static void Init()
{
AssetUsageDetectorWindow window = GetWindow<AssetUsageDetectorWindow>();
window.titleContent = new GUIContent( "Asset Usage Detector" );
window.minSize = new Vector2( 325f, 220f );
window.Show();
}
private void OnDisable()
{
if( core != null )
core.SaveCache();
}
private void OnDestroy()
{
if( searchResult != null && currentPhase == Phase.Complete && !EditorApplication.isPlaying && searchResult.InitialSceneSetupConfigured )
{
if( EditorUtility.DisplayDialog( "Scenes", "Restore initial scene setup?", "Yes", "Leave it as is" ) )
searchResult.RestoreInitialSceneSetup();
}
}
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();
}
}
private void OnGUI()
{
// Make the window scrollable
scrollPosition = EditorGUILayout.BeginScrollView( scrollPosition, Utilities.GL_EXPAND_WIDTH, Utilities.GL_EXPAND_HEIGHT );
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 we are stuck at this phase, then we have encountered an exception
GUILayout.Label( ". . . Something went wrong, check console . . ." );
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup (Recommended)", restoreInitialSceneSetup );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
}
else if( currentPhase == Phase.Setup )
{
if( ExposeSearchedObjects() )
errorMessage = string.Empty;
GUILayout.Space( 10 );
GUILayout.Box( "SEARCH IN", Utilities.GL_EXPAND_WIDTH );
searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project view (Assets folder)", searchInAssetsFolder );
if( searchInAssetsFolder )
{
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
GUILayout.BeginVertical();
ExposeAssetsToSearch();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
GUILayout.Space( 10 );
if( EditorApplication.isPlaying )
{
searchInAllScenes = false;
searchInScenesInBuild = false;
}
else if( searchInAllScenes )
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 )
GUI.enabled = true;
searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes );
GUI.enabled = true;
GUILayout.Space( 10 );
GUILayout.Box( "SEARCH SETTINGS", Utilities.GL_EXPAND_WIDTH );
GUILayout.BeginHorizontal();
GUILayout.Label( new GUIContent( "> Search depth: " + searchDepthLimit, "Depth limit for recursively searching variables of objects" ), Utilities.GL_WIDTH_250 );
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 (can be slow):" );
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 );
// 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 && !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;
}
}
}
else if( currentPhase == Phase.Complete )
{
// Draw the results of the search
GUI.enabled = false;
ExposeSearchedObjects();
GUILayout.Space( 10 );
GUI.enabled = true;
restoreInitialSceneSetup = EditorGUILayout.ToggleLeft( "Restore initial scene setup after search is reset (Recommended)", restoreInitialSceneSetup );
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
ReturnToSetupPhase( restoreInitialSceneSetup );
if( searchResult == null )
{
EditorGUILayout.HelpBox( "ERROR: searchResult is null", MessageType.Error );
return;
}
Color c = GUI.color;
GUI.color = Color.green;
GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.GL_EXPAND_WIDTH );
GUI.color = c;
GUILayout.Space( 10 );
if( searchResult.Count == 0 )
GUILayout.Box( "No results found...", Utilities.GL_EXPAND_WIDTH );
else
{
GUILayout.BeginHorizontal();
// Select all the references after filtering them (select only the GameObject's)
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
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( "Show tooltips", searchResultDrawParameters.showTooltips );
GUILayout.Space( 10 );
GUILayout.Label( "Path drawing mode:" );
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references (can be slow with too many references)", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant unique parts of the complete paths that start with a UnityEngine.Object", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space( 35 );
if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of complete paths that are unique", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) )
searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest;
GUILayout.EndHorizontal();
searchResult.DrawOnGUI( searchResultDrawParameters );
}
}
GUILayout.Space( 10 );
GUILayout.EndVertical();
EditorGUILayout.EndScrollView();
}
// Exposes objectsToSearch as an array field on GUI
private bool ExposeSearchedObjects()
{
bool hasChanged = false;
bool guiEnabled = GUI.enabled;
Event ev = Event.current;
GUILayout.BeginHorizontal();
GUILayout.Label( "Asset(s):" );
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;
objectsToSearch.Add( new ObjectToSearch( draggedObjects[i] ) );
}
}
}
}
ev.Use();
}
if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) )
objectsToSearch.Insert( 0, new ObjectToSearch( null ) );
}
GUILayout.EndHorizontal();
for( int i = 0; i < objectsToSearch.Count; i++ )
{
ObjectToSearch objToSearch = objectsToSearch[i];
GUI.changed = false;
GUILayout.BeginHorizontal();
Object prevAssetToSearch = objToSearch.obj;
objToSearch.obj = EditorGUILayout.ObjectField( "", objToSearch.obj, typeof( Object ), true );
if( GUI.changed && prevAssetToSearch != objToSearch.obj )
{
hasChanged = true;
objToSearch.RefreshSubAssets();
}
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();
}
}
// Check if all open scenes are saved (not dirty)
private bool AreScenesSaved()
{
for( int i = 0; i < EditorSceneManager.loadedSceneCount; i++ )
{
Scene scene = EditorSceneManager.GetSceneAt( i );
if( scene.isDirty || string.IsNullOrEmpty( scene.path ) )
return false;
}
return true;
}
private void ReturnToSetupPhase( bool restoreInitialSceneSetup )
{
if( searchResult != null && restoreInitialSceneSetup && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
return;
searchResult = null;
errorMessage = string.Empty;
currentPhase = Phase.Setup;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 271a22c69c3d96c4dbdd04cca415a840
timeCreated: 1520032279
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,106 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AssetUsageDetectorNamespace
{
public class EmptyEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
public T Current { get { return default( T ); } }
object IEnumerator.Current { get { return Current; } }
public void Dispose() { }
public void Reset() { }
public bool MoveNext()
{
return false;
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
}
public class ObjectToSearchEnumerator : IEnumerable<Object>, IEnumerator<Object>
{
public Object Current
{
get
{
if( subAssetIndex < 0 )
return source[index].obj;
return source[index].subAssets[subAssetIndex].subAsset;
}
}
object IEnumerator.Current { get { return Current; } }
private List<ObjectToSearch> source;
private int index;
private int subAssetIndex;
public ObjectToSearchEnumerator( List<ObjectToSearch> source )
{
this.source = source;
Reset();
}
public void Dispose()
{
source = null;
}
public bool MoveNext()
{
if( subAssetIndex < -1 )
{
subAssetIndex = -1;
if( ++index >= source.Count )
return false;
// Skip folder assets in the enumeration, AssetUsageDetector expands encountered folders automatically
// and we don't want that to happen as source[index].subAssets already contains the folder's contents
if( !source[index].obj.IsFolder() )
return true;
}
List<ObjectToSearch.SubAsset> subAssets = source[index].subAssets;
if( subAssets != null )
{
while( ++subAssetIndex < subAssets.Count && !subAssets[subAssetIndex].shouldSearch )
continue;
if( subAssetIndex < subAssets.Count )
return true;
}
subAssetIndex = -2;
return MoveNext();
}
public void Reset()
{
index = -1;
subAssetIndex = -2;
}
public IEnumerator<Object> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 894047c47ce45cf40939dae24afcc72b
timeCreated: 1562079461
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -9,8 +9,21 @@ namespace AssetUsageDetectorNamespace
[Serializable]
public class ObjectToSearch
{
[Serializable]
public class SubAsset
{
public Object subAsset;
public bool shouldSearch;
public SubAsset( Object subAsset, bool shouldSearch )
{
this.subAsset = subAsset;
this.shouldSearch = shouldSearch;
}
}
public Object obj;
public List<SubAssetToSearch> subAssets;
public List<SubAsset> subAssets;
public bool showSubAssetsFoldout;
private static MonoScript[] monoScriptsInProject;
@@ -25,7 +38,7 @@ namespace AssetUsageDetectorNamespace
public void RefreshSubAssets()
{
if( subAssets == null )
subAssets = new List<SubAssetToSearch>();
subAssets = new List<SubAsset>();
else
subAssets.Clear();
@@ -35,6 +48,7 @@ namespace AssetUsageDetectorNamespace
currentSubAssets.Clear();
AddSubAssets( obj, false );
currentSubAssets.Clear();
}
private void AddSubAssets( Object target, bool includeTarget )
@@ -49,23 +63,17 @@ namespace AssetUsageDetectorNamespace
{
if( !currentSubAssets.Contains( target ) )
{
subAssets.Add( new SubAssetToSearch( target, true ) );
subAssets.Add( new SubAsset( target, true ) );
currentSubAssets.Add( target );
}
}
else
{
// If asset is a directory, add all of its contents as sub-assets recursively
string targetPath = AssetDatabase.GetAssetPath( target );
if( target is DefaultAsset && AssetDatabase.IsValidFolder( targetPath ) )
if( target.IsFolder() )
{
string[] folderContents = AssetDatabase.FindAssets( "", new string[] { targetPath } );
for( int i = 0; i < folderContents.Length; i++ )
{
string filePath = AssetDatabase.GUIDToAssetPath( folderContents[i] );
if( !string.IsNullOrEmpty( filePath ) && !AssetDatabase.IsValidFolder( filePath ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
}
foreach( string filePath in Utilities.EnumerateFolderContents( target ) )
AddSubAssets( AssetDatabase.LoadAssetAtPath<Object>( filePath ), true );
return;
}
@@ -84,7 +92,7 @@ namespace AssetUsageDetectorNamespace
if( asset != target )
{
subAssets.Add( new SubAssetToSearch( asset, true ) );
subAssets.Add( new SubAsset( asset, true ) );
currentSubAssets.Add( asset );
}
@@ -114,7 +122,7 @@ namespace AssetUsageDetectorNamespace
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
{
subAssets.Add( new SubAssetToSearch( monoScriptsInProject[j], true ) );
subAssets.Add( new SubAsset( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
}
}
@@ -122,17 +130,4 @@ namespace AssetUsageDetectorNamespace
}
}
}
[Serializable]
public class SubAssetToSearch
{
public Object subAsset;
public bool shouldSearch;
public SubAssetToSearch( Object subAsset, bool shouldSearch )
{
this.subAsset = subAsset;
this.shouldSearch = shouldSearch;
}
}
}
@@ -1,14 +1,212 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
// Custom class to hold the results for a single scene or Assets folder
[Serializable]
public class ReferenceHolder : ISerializationCallbackReceiver
public class SearchResultDrawParameters
{
public PathDrawingMode pathDrawingMode;
public bool showTooltips;
public string tooltip;
public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips )
{
this.pathDrawingMode = pathDrawingMode;
this.showTooltips = showTooltips;
}
}
// Custom class to hold search results
[Serializable]
public class SearchResult : ISerializationCallbackReceiver
{
// Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html
[Serializable]
public class SerializableResultGroup
{
public string title;
public bool clickable;
public List<int> initialSerializedNodes;
}
[Serializable]
public class SerializableNode
{
public int instanceId;
public bool isUnityObject;
public string description;
public List<int> links;
public List<string> linkDescriptions;
}
private List<SearchResultGroup> result;
private SceneSetup[] initialSceneSetup;
private List<SerializableNode> serializedNodes;
private List<SerializableResultGroup> serializedGroups;
public int Count { get { return result.Count; } }
public SearchResultGroup this[int index] { get { return result[index]; } }
public bool SearchCompletedSuccessfully { get { return result != null; } }
public bool InitialSceneSetupConfigured { get { return initialSceneSetup != null; } }
public SearchResult( List<SearchResultGroup> result, SceneSetup[] initialSceneSetup )
{
if( result == null )
result = new List<SearchResultGroup>( 0 );
this.result = result;
this.initialSceneSetup = initialSceneSetup;
}
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
parameters.tooltip = null;
for( int i = 0; i < result.Count; i++ )
result[i].DrawOnGUI( parameters );
if( parameters.tooltip != null )
{
// Show tooltip at mouse position
Vector2 mousePos = Event.current.mousePosition;
Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( parameters.tooltip ) );
GUI.Box( new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ), parameters.tooltip, Utilities.TooltipGUIStyle );
}
}
public Object[] SelectAllAsObjects()
{
HashSet<Object> uniqueObjects = new HashSet<Object>();
for( int i = 0; i < result.Count; i++ )
result[i].AddObjectsTo( uniqueObjects );
if( uniqueObjects.Count > 0 )
{
Object[] objects = new Object[uniqueObjects.Count];
uniqueObjects.CopyTo( objects );
return objects;
}
return null;
}
public GameObject[] SelectAllAsGameObjects()
{
HashSet<GameObject> uniqueGameObjects = new HashSet<GameObject>();
for( int i = 0; i < result.Count; i++ )
result[i].AddGameObjectsTo( uniqueGameObjects );
if( uniqueGameObjects.Count > 0 )
{
GameObject[] objects = new GameObject[uniqueGameObjects.Count];
uniqueGameObjects.CopyTo( objects );
return objects;
}
return null;
}
// Close the scenes that were not part of the initial scene setup
// Returns true if initial scene setup is restored successfully
public bool RestoreInitialSceneSetup()
{
if( initialSceneSetup == null )
return true;
if( EditorApplication.isPlaying || !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo() )
return false;
SceneSetup[] sceneFinalSetup = EditorSceneManager.GetSceneManagerSetup();
for( int i = 0; i < sceneFinalSetup.Length; i++ )
{
bool sceneIsOneOfInitials = false;
for( int j = 0; j < initialSceneSetup.Length; j++ )
{
if( sceneFinalSetup[i].path == initialSceneSetup[j].path )
{
sceneIsOneOfInitials = true;
break;
}
}
if( !sceneIsOneOfInitials )
EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( sceneFinalSetup[i].path ), true );
}
for( int i = 0; i < initialSceneSetup.Length; i++ )
{
if( !initialSceneSetup[i].isLoaded )
EditorSceneManager.CloseScene( EditorSceneManager.GetSceneByPath( initialSceneSetup[i].path ), false );
}
initialSceneSetup = null;
return true;
}
// Assembly reloading; serialize nodes in a way that Unity can serialize
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
if( result == null )
return;
if( serializedGroups == null )
serializedGroups = new List<SerializableResultGroup>( result.Count );
else
serializedGroups.Clear();
if( serializedNodes == null )
serializedNodes = new List<SerializableNode>( result.Count * 16 );
else
serializedNodes.Clear();
Dictionary<ReferenceNode, int> nodeToIndex = new Dictionary<ReferenceNode, int>( result.Count * 16 );
for( int i = 0; i < result.Count; i++ )
serializedGroups.Add( result[i].Serialize( nodeToIndex, serializedNodes ) );
}
// Assembly reloaded; deserialize nodes to construct the original graph
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if( serializedGroups == null || serializedNodes == null )
return;
if( result == null )
result = new List<SearchResultGroup>( serializedGroups.Count );
else
result.Clear();
List<ReferenceNode> allNodes = new List<ReferenceNode>( serializedNodes.Count );
for( int i = 0; i < serializedNodes.Count; i++ )
allNodes.Add( new ReferenceNode() );
for( int i = 0; i < serializedNodes.Count; i++ )
allNodes[i].Deserialize( serializedNodes[i], allNodes );
for( int i = 0; i < serializedGroups.Count; i++ )
{
result.Add( new SearchResultGroup( serializedGroups[i].title, serializedGroups[i].clickable ) );
result[i].Deserialize( serializedGroups[i], allNodes );
}
serializedNodes.Clear();
serializedGroups.Clear();
}
}
// Custom class to hold the results for a single scene or Assets folder
public class SearchResultGroup
{
// Custom struct to hold a single path to a reference
public struct ReferencePath
@@ -23,34 +221,21 @@ namespace AssetUsageDetectorNamespace
}
}
// Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html
[Serializable]
public class SerializableNode
{
public int instanceId;
public bool isUnityObject;
public string description;
private readonly string title;
private readonly bool clickable;
public List<int> links;
public List<string> linkDescriptions;
}
private string title;
private bool clickable;
private List<ReferenceNode> references;
private readonly List<ReferenceNode> references;
private List<ReferencePath> referencePathsShortUnique;
private List<ReferencePath> referencePathsShortest;
private List<SerializableNode> serializedNodes;
private List<int> initialSerializedNodes;
public int NumberOfReferences { get { return references.Count; } }
public ReferenceNode this[int index] { get { return references[index]; } }
public ReferenceHolder( string title, bool clickable )
public SearchResultGroup( string title, bool clickable )
{
this.title = title;
this.clickable = clickable;
references = new List<ReferenceNode>();
referencePathsShortUnique = null;
referencePathsShortest = null;
@@ -150,7 +335,7 @@ namespace AssetUsageDetectorNamespace
}
// Draw the results found for this container
public void DrawOnGUI( PathDrawingMode pathDrawingMode )
public void DrawOnGUI( SearchResultDrawParameters parameters )
{
Color c = GUI.color;
GUI.color = Color.cyan;
@@ -163,13 +348,12 @@ namespace AssetUsageDetectorNamespace
GUI.color = Color.yellow;
if( pathDrawingMode == PathDrawingMode.Full )
if( parameters.pathDrawingMode == PathDrawingMode.Full )
{
for( int i = 0; i < references.Count; i++ )
{
GUILayout.Space( 5 );
references[i].DrawOnGUIRecursively();
references[i].DrawOnGUIRecursively( parameters, null );
}
}
else
@@ -178,7 +362,7 @@ namespace AssetUsageDetectorNamespace
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( pathDrawingMode == PathDrawingMode.ShortRelevantParts )
if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
@@ -190,13 +374,13 @@ namespace AssetUsageDetectorNamespace
GUILayout.BeginHorizontal();
ReferencePath path = pathsToDraw[i];
path.startNode.DrawOnGUI( null );
path.startNode.DrawOnGUI( parameters, null );
ReferenceNode currentNode = path.startNode;
for( int j = 0; j < path.pathLinksToFollow.Length; j++ )
{
ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]];
link.targetNode.DrawOnGUI( link.description );
link.targetNode.DrawOnGUI( parameters, link.description );
currentNode = link.targetNode;
}
@@ -209,53 +393,37 @@ namespace AssetUsageDetectorNamespace
GUILayout.Space( 10 );
}
// Assembly reloading; serialize nodes in a way that Unity can serialize
public void OnBeforeSerialize()
// Serialize this result group
public SearchResult.SerializableResultGroup Serialize( Dictionary<ReferenceNode, int> nodeToIndex, List<SearchResult.SerializableNode> serializedNodes )
{
if( references == null )
return;
SearchResult.SerializableResultGroup serializedResultGroup = new SearchResult.SerializableResultGroup()
{
title = title,
clickable = clickable
};
if( serializedNodes == null )
serializedNodes = new List<SerializableNode>( references.Count * 5 );
else
serializedNodes.Clear();
if( references != null )
{
serializedResultGroup.initialSerializedNodes = new List<int>( references.Count );
if( initialSerializedNodes == null )
initialSerializedNodes = new List<int>( references.Count );
else
initialSerializedNodes.Clear();
for( int i = 0; i < references.Count; i++ )
serializedResultGroup.initialSerializedNodes.Add( references[i].SerializeRecursively( nodeToIndex, serializedNodes ) );
}
Dictionary<ReferenceNode, int> nodeToIndex = new Dictionary<ReferenceNode, int>( references.Count * 5 );
for( int i = 0; i < references.Count; i++ )
initialSerializedNodes.Add( references[i].SerializeRecursively( nodeToIndex, serializedNodes ) );
return serializedResultGroup;
}
// Assembly reloaded; deserialize nodes to construct the original graph
public void OnAfterDeserialize()
// Deserialize this result group from the serialized data
public void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List<ReferenceNode> allNodes )
{
if( initialSerializedNodes == null || serializedNodes == null )
return;
if( references == null )
references = new List<ReferenceNode>( initialSerializedNodes.Count );
else
references.Clear();
List<ReferenceNode> allNodes = new List<ReferenceNode>( serializedNodes.Count );
for( int i = 0; i < serializedNodes.Count; i++ )
allNodes.Add( new ReferenceNode() );
for( int i = 0; i < serializedNodes.Count; i++ )
allNodes[i].Deserialize( serializedNodes[i], allNodes );
for( int i = 0; i < initialSerializedNodes.Count; i++ )
references.Add( allNodes[initialSerializedNodes[i]] );
if( serializedResultGroup.initialSerializedNodes != null )
{
for( int i = 0; i < serializedResultGroup.initialSerializedNodes.Count; i++ )
references.Add( allNodes[serializedResultGroup.initialSerializedNodes[i]] );
}
referencePathsShortUnique = null;
referencePathsShortest = null;
serializedNodes.Clear();
initialSerializedNodes.Clear();
}
}
@@ -349,13 +517,13 @@ namespace AssetUsageDetectorNamespace
}
// Calculate short unique paths that start with this node
public void CalculateShortUniquePaths( List<ReferenceHolder.ReferencePath> currentPaths )
public void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> currentPaths )
{
CalculateShortUniquePaths( currentPaths, new List<ReferenceNode>( 8 ), new List<int>( 8 ) { -1 }, 0 );
}
// Just some boring calculations to find the short unique paths recursively
private void CalculateShortUniquePaths( List<ReferenceHolder.ReferencePath> shortestPaths, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath )
private void CalculateShortUniquePaths( List<SearchResultGroup.ReferencePath> shortestPaths, List<ReferenceNode> currentPath, List<int> currentPathIndices, int latestObjectIndexInPath )
{
int currentIndex = currentPath.Count;
currentPath.Add( this );
@@ -390,7 +558,7 @@ namespace AssetUsageDetectorNamespace
for( int i = latestObjectIndexInPath + 1, j = 0; i < currentPathIndices.Count; i++, j++ )
pathIndices[j] = currentPathIndices[i];
shortestPaths.Add( new ReferenceHolder.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) );
shortestPaths.Add( new SearchResultGroup.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) );
}
}
else
@@ -410,11 +578,11 @@ namespace AssetUsageDetectorNamespace
}
// Draw all the paths that start with this node on GUI recursively
public void DrawOnGUIRecursively( string linkToPrevNodeDescription = null )
public void DrawOnGUIRecursively( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
{
GUILayout.BeginHorizontal();
DrawOnGUI( linkToPrevNodeDescription );
DrawOnGUI( parameters, linkToPrevNodeDescription );
if( links.Count > 0 )
{
@@ -423,7 +591,7 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < links.Count; i++ )
{
ReferenceNode next = links[i].targetNode;
next.DrawOnGUIRecursively( links[i].description );
next.DrawOnGUIRecursively( parameters, links[i].description );
}
GUILayout.EndVertical();
@@ -433,36 +601,27 @@ namespace AssetUsageDetectorNamespace
}
// Draw only this node on GUI
public void DrawOnGUI( string linkToPrevNodeDescription )
public void DrawOnGUI( SearchResultDrawParameters parameters, string linkToPrevNodeDescription )
{
string label = GetNodeContent( linkToPrevNodeDescription );
string label = string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description );
if( GUILayout.Button( label, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_HEIGHT ) )
{
// If a reference is clicked, highlight it (either on Hierarchy view or Project view)
UnityObject.SelectInEditor();
}
if( AssetUsageDetector.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) )
AssetUsageDetector.tooltip = label;
}
// Get the string representation of this node
private string GetNodeContent( string linkToPrevNodeDescription = null )
{
if( !string.IsNullOrEmpty( linkToPrevNodeDescription ) )
return linkToPrevNodeDescription + "\n" + description;
return description;
if( parameters.showTooltips && Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains( Event.current.mousePosition ) )
parameters.tooltip = label;
}
// Serialize this node and its connected nodes recursively
public int SerializeRecursively( Dictionary<ReferenceNode, int> nodeToIndex, List<ReferenceHolder.SerializableNode> serializedNodes )
public int SerializeRecursively( Dictionary<ReferenceNode, int> nodeToIndex, List<SearchResult.SerializableNode> serializedNodes )
{
int index;
if( nodeToIndex.TryGetValue( this, out index ) )
return index;
ReferenceHolder.SerializableNode serializedNode = new ReferenceHolder.SerializableNode()
SearchResult.SerializableNode serializedNode = new SearchResult.SerializableNode()
{
instanceId = instanceId ?? 0,
isUnityObject = instanceId.HasValue,
@@ -489,7 +648,7 @@ namespace AssetUsageDetectorNamespace
}
// Deserialize this node and its links from the serialized data
public void Deserialize( ReferenceHolder.SerializableNode serializedNode, List<ReferenceNode> allNodes )
public void Deserialize( SearchResult.SerializableNode serializedNode, List<ReferenceNode> allNodes )
{
if( serializedNode.isUnityObject )
instanceId = serializedNode.instanceId;
+55 -1
View File
@@ -15,6 +15,8 @@ namespace AssetUsageDetectorNamespace
typeof( Quaternion ), typeof( Color ), typeof( Color32 ), typeof( LayerMask ),
typeof( Matrix4x4 ), typeof( AnimationCurve ), typeof( Gradient ), typeof( RectOffset ) };
private static readonly HashSet<string> folderContentsSet = new HashSet<string>();
public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true );
public static readonly GUILayoutOption GL_EXPAND_HEIGHT = GUILayout.ExpandHeight( true );
public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 );
@@ -23,7 +25,7 @@ namespace AssetUsageDetectorNamespace
public static readonly GUILayoutOption GL_HEIGHT_30 = GUILayout.Height( 30 );
public static readonly GUILayoutOption GL_HEIGHT_35 = GUILayout.Height( 35 );
public static readonly GUILayoutOption GL_HEIGHT_40 = GUILayout.Height( 40 );
private static GUIStyle m_boxGUIStyle; // GUIStyle used to draw the results of the search
public static GUIStyle BoxGUIStyle
{
@@ -93,6 +95,30 @@ namespace AssetUsageDetectorNamespace
return obj is Object && AssetDatabase.Contains( (Object) obj );
}
// Check if object is a folder asset
public static bool IsFolder( this Object obj )
{
return obj is DefaultAsset && AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( obj ) );
}
// Returns an enumerator to iterate through all asset paths in the folder
public static IEnumerable<string> EnumerateFolderContents( Object folderAsset )
{
string[] folderContents = AssetDatabase.FindAssets( "", new string[] { AssetDatabase.GetAssetPath( folderAsset ) } );
if( folderContents == null )
return new EmptyEnumerator<string>();
folderContentsSet.Clear();
for( int i = 0; i < folderContents.Length; i++ )
{
string filePath = AssetDatabase.GUIDToAssetPath( folderContents[i] );
if( !string.IsNullOrEmpty( filePath ) && !AssetDatabase.IsValidFolder( filePath ) )
folderContentsSet.Add( filePath );
}
return folderContentsSet;
}
// Select an object in the editor
public static void SelectInEditor( this Object obj )
{
@@ -269,5 +295,33 @@ namespace AssetUsageDetectorNamespace
return null;
}
public static bool IsEmpty( this List<ObjectToSearch> objectsToSearch )
{
if( objectsToSearch == null )
return true;
for( int i = 0; i < objectsToSearch.Count; i++ )
{
if( objectsToSearch[i].obj != null && !objectsToSearch[i].obj.Equals( null ) )
return false;
}
return true;
}
public static bool IsEmpty( this List<Object> searchInAssetsSubset )
{
if( searchInAssetsSubset == null )
return true;
for( int i = 0; i < searchInAssetsSubset.Count; i++ )
{
if( searchInAssetsSubset[i] != null && !searchInAssetsSubset[i].Equals( null ) )
return false;
}
return true;
}
}
}