- Caching asset dependencies for faster calculations

- Dependencies are checked via their paths, so loading the asset is not necessary and much less memory will be used
- Separated AssetUsageDetector.cs into smaller classes
This commit is contained in:
Süleyman Yasir KULA
2019-07-01 23:27:21 +03:00
parent 06ff1db30b
commit 8d3e8e7738
14 changed files with 2729 additions and 2424 deletions
+9
View File
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: c1764d69117881843b761dc14ca276d4
folderAsset: yes
timeCreated: 1561225368
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
+9
View File
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 19f677a9eb83d3942af6d4c5fa8dbeee
folderAsset: yes
timeCreated: 1520032274
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2c0dea52dcdb16e4e9b13f8dacc1590f
timeCreated: 1520032279
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,138 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
[Serializable]
public class ObjectToSearch
{
public Object obj;
public List<SubAssetToSearch> subAssets;
public bool showSubAssetsFoldout;
private static MonoScript[] monoScriptsInProject;
private static HashSet<Object> currentSubAssets;
public ObjectToSearch( Object obj )
{
this.obj = obj;
RefreshSubAssets();
}
public void RefreshSubAssets()
{
if( subAssets == null )
subAssets = new List<SubAssetToSearch>();
else
subAssets.Clear();
if( currentSubAssets == null )
currentSubAssets = new HashSet<Object>();
else
currentSubAssets.Clear();
AddSubAssets( obj, false );
}
private void AddSubAssets( Object target, bool includeTarget )
{
if( target == null || target.Equals( null ) )
return;
if( !target.IsAsset() || !AssetDatabase.IsMainAsset( target ) || target is SceneAsset )
return;
if( includeTarget )
{
if( !currentSubAssets.Contains( target ) )
{
subAssets.Add( new SubAssetToSearch( 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 ) )
{
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 );
}
return;
}
}
// Find sub-asset(s) of the asset (if any)
Object[] assets = AssetDatabase.LoadAllAssetsAtPath( AssetDatabase.GetAssetPath( target ) );
for( int i = 0; i < assets.Length; i++ )
{
Object asset = assets[i];
if( asset == null || asset.Equals( null ) || asset is Component )
continue;
if( currentSubAssets.Contains( asset ) )
continue;
if( asset != target )
{
subAssets.Add( new SubAssetToSearch( asset, true ) );
currentSubAssets.Add( asset );
}
// MonoScripts are a special case such that other MonoScript objects
// that extend this MonoScript are also considered a sub-asset
if( asset is MonoScript )
{
Type monoScriptType = ( (MonoScript) asset ).GetClass();
if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) )
continue;
// Find all MonoScript objects in the project
if( monoScriptsInProject == null )
{
string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" );
monoScriptsInProject = new MonoScript[monoScriptGuids.Length];
for( int k = 0; k < monoScriptGuids.Length; k++ )
monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath<MonoScript>( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) );
}
// Add any MonoScript objects that extend this MonoScript as a sub-asset
for( int j = 0; j < monoScriptsInProject.Length; j++ )
{
Type otherMonoScriptType = monoScriptsInProject[j].GetClass();
if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) )
continue;
if( !currentSubAssets.Contains( monoScriptsInProject[j] ) )
{
subAssets.Add( new SubAssetToSearch( monoScriptsInProject[j], true ) );
currentSubAssets.Add( monoScriptsInProject[j] );
}
}
}
}
}
}
[Serializable]
public class SubAssetToSearch
{
public Object subAsset;
public bool shouldSearch;
public SubAssetToSearch( Object subAsset, bool shouldSearch )
{
this.subAsset = subAsset;
this.shouldSearch = shouldSearch;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 66d5a144a723fea40945afc069d4231d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,513 @@
using System;
using System.Collections.Generic;
using UnityEditor;
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
{
// Custom struct to hold a single path to a reference
public struct ReferencePath
{
public readonly ReferenceNode startNode;
public readonly int[] pathLinksToFollow;
public ReferencePath( ReferenceNode startNode, int[] pathIndices )
{
this.startNode = startNode;
pathLinksToFollow = pathIndices;
}
}
// Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html
[Serializable]
public class SerializableNode
{
public int instanceId;
public bool isUnityObject;
public string description;
public List<int> links;
public List<string> linkDescriptions;
}
private string title;
private bool clickable;
private 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 ReferenceHolder( string title, bool clickable )
{
this.title = title;
this.clickable = clickable;
references = new List<ReferenceNode>();
referencePathsShortUnique = null;
referencePathsShortest = null;
}
// Add a reference to the list
public void AddReference( ReferenceNode node )
{
references.Add( node );
}
// Initializes commonly used variables of the nodes
public void InitializeNodes()
{
for( int i = 0; i < references.Count; i++ )
references[i].InitializeRecursively();
}
// Check if node exists in this results set
public bool Contains( ReferenceNode node )
{
for( int i = 0; i < references.Count; i++ )
{
if( references[i] == node )
return true;
}
return false;
}
// Add all the Object's in this container to the set
public void AddObjectsTo( HashSet<Object> objectsSet )
{
CalculateShortestPathsToReferences();
for( int i = 0; i < referencePathsShortUnique.Count; i++ )
{
Object obj = referencePathsShortUnique[i].startNode.UnityObject;
if( obj != null && !obj.Equals( null ) )
objectsSet.Add( obj );
}
}
// Add all the GameObject's in this container to the set
public void AddGameObjectsTo( HashSet<GameObject> gameObjectsSet )
{
CalculateShortestPathsToReferences();
for( int i = 0; i < referencePathsShortUnique.Count; i++ )
{
Object obj = referencePathsShortUnique[i].startNode.UnityObject;
if( obj != null && !obj.Equals( null ) )
{
if( obj is GameObject )
gameObjectsSet.Add( (GameObject) obj );
else if( obj is Component )
gameObjectsSet.Add( ( (Component) obj ).gameObject );
}
}
}
// Calculate short unique paths to the references
public void CalculateShortestPathsToReferences()
{
if( referencePathsShortUnique != null )
return;
referencePathsShortUnique = new List<ReferencePath>( 32 );
for( int i = 0; i < references.Count; i++ )
references[i].CalculateShortUniquePaths( referencePathsShortUnique );
referencePathsShortest = new List<ReferencePath>( referencePathsShortUnique.Count );
for( int i = 0; i < referencePathsShortUnique.Count; i++ )
{
int[] linksToFollow = referencePathsShortUnique[i].pathLinksToFollow;
// Find the last two nodes in this path
ReferenceNode nodeBeforeLast = referencePathsShortUnique[i].startNode;
for( int j = 0; j < linksToFollow.Length - 1; j++ )
nodeBeforeLast = nodeBeforeLast[linksToFollow[j]].targetNode;
// Check if these two nodes are unique
bool isUnique = true;
for( int j = 0; j < referencePathsShortest.Count; j++ )
{
ReferencePath path = referencePathsShortest[j];
if( path.startNode == nodeBeforeLast && path.pathLinksToFollow[0] == linksToFollow[linksToFollow.Length - 1] )
{
isUnique = false;
break;
}
}
if( isUnique )
referencePathsShortest.Add( new ReferencePath( nodeBeforeLast, new int[1] { linksToFollow[linksToFollow.Length - 1] } ) );
}
}
// Draw the results found for this container
public void DrawOnGUI( PathDrawingMode pathDrawingMode )
{
Color c = GUI.color;
GUI.color = Color.cyan;
if( GUILayout.Button( title, Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_40 ) && clickable )
{
// If the container (scene, usually) is clicked, highlight it on Project view
AssetDatabase.LoadAssetAtPath<SceneAsset>( title ).SelectInEditor();
}
GUI.color = Color.yellow;
if( pathDrawingMode == PathDrawingMode.Full )
{
for( int i = 0; i < references.Count; i++ )
{
GUILayout.Space( 5 );
references[i].DrawOnGUIRecursively();
}
}
else
{
if( referencePathsShortUnique == null )
CalculateShortestPathsToReferences();
List<ReferencePath> pathsToDraw;
if( pathDrawingMode == PathDrawingMode.ShortRelevantParts )
pathsToDraw = referencePathsShortUnique;
else
pathsToDraw = referencePathsShortest;
for( int i = 0; i < pathsToDraw.Count; i++ )
{
GUILayout.Space( 5 );
GUILayout.BeginHorizontal();
ReferencePath path = pathsToDraw[i];
path.startNode.DrawOnGUI( 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 );
currentNode = link.targetNode;
}
GUILayout.EndHorizontal();
}
}
GUI.color = c;
GUILayout.Space( 10 );
}
// Assembly reloading; serialize nodes in a way that Unity can serialize
public void OnBeforeSerialize()
{
if( references == null )
return;
if( serializedNodes == null )
serializedNodes = new List<SerializableNode>( references.Count * 5 );
else
serializedNodes.Clear();
if( initialSerializedNodes == null )
initialSerializedNodes = new List<int>( references.Count );
else
initialSerializedNodes.Clear();
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 ) );
}
// Assembly reloaded; deserialize nodes to construct the original graph
public void OnAfterDeserialize()
{
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]] );
referencePathsShortUnique = null;
referencePathsShortest = null;
serializedNodes.Clear();
initialSerializedNodes.Clear();
}
}
// Custom class to hold an object in the path to a reference as a node
public class ReferenceNode
{
public struct Link
{
public readonly ReferenceNode targetNode;
public readonly string description;
public Link( ReferenceNode targetNode, string description )
{
this.targetNode = targetNode;
this.description = description;
}
}
// Unique identifier is used while serializing the node
private static int uid_last = 0;
private readonly int uid;
public object nodeObject;
private readonly List<Link> links;
private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise
private string description; // String to print on this node
public Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } }
public int NumberOfOutgoingLinks { get { return links.Count; } }
public Link this[int index] { get { return links[index]; } }
public ReferenceNode()
{
links = new List<Link>( 2 );
uid = uid_last++;
}
public ReferenceNode( object obj ) : this()
{
nodeObject = obj;
}
// Add a one-way connection to another node
public void AddLinkTo( ReferenceNode nextNode, string description = null )
{
if( nextNode != null )
{
if( !string.IsNullOrEmpty( description ) )
description = "[" + description + "]";
links.Add( new Link( nextNode, description ) );
}
}
// Initialize node's commonly used variables
public void InitializeRecursively()
{
if( description != null ) // Already initialized
return;
Object unityObject = nodeObject as Object;
if( unityObject != null )
{
instanceId = unityObject.GetInstanceID();
description = unityObject.name + " (" + unityObject.GetType() + ")";
}
else if( nodeObject != null )
{
instanceId = null;
description = nodeObject.GetType() + " object";
}
else
{
instanceId = null;
description = "<<destroyed>>";
}
nodeObject = null; // don't hold Object reference, allow Unity to GC used memory
for( int i = 0; i < links.Count; i++ )
links[i].targetNode.InitializeRecursively();
}
// Clear this node so that it can be reused later
public void Clear()
{
nodeObject = null;
links.Clear();
}
// Calculate short unique paths that start with this node
public void CalculateShortUniquePaths( List<ReferenceHolder.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 )
{
int currentIndex = currentPath.Count;
currentPath.Add( this );
if( links.Count == 0 )
{
// Check if the path to the reference is unique (not discovered so far)
bool isUnique = true;
for( int i = 0; i < shortestPaths.Count; i++ )
{
if( shortestPaths[i].startNode == currentPath[latestObjectIndexInPath] && shortestPaths[i].pathLinksToFollow.Length == currentPathIndices.Count - latestObjectIndexInPath - 1 )
{
int j = latestObjectIndexInPath + 1;
for( int k = 0; j < currentPathIndices.Count; j++, k++ )
{
if( shortestPaths[i].pathLinksToFollow[k] != currentPathIndices[j] )
break;
}
if( j == currentPathIndices.Count )
{
isUnique = false;
break;
}
}
}
// Don't allow duplicate short paths
if( isUnique )
{
int[] pathIndices = new int[currentPathIndices.Count - latestObjectIndexInPath - 1];
for( int i = latestObjectIndexInPath + 1, j = 0; i < currentPathIndices.Count; i++, j++ )
pathIndices[j] = currentPathIndices[i];
shortestPaths.Add( new ReferenceHolder.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) );
}
}
else
{
if( instanceId.HasValue ) // nodeObject is Unity object
latestObjectIndexInPath = currentIndex;
for( int i = 0; i < links.Count; i++ )
{
currentPathIndices.Add( i );
links[i].targetNode.CalculateShortUniquePaths( shortestPaths, currentPath, currentPathIndices, latestObjectIndexInPath );
currentPathIndices.RemoveAt( currentIndex + 1 );
}
}
currentPath.RemoveAt( currentIndex );
}
// Draw all the paths that start with this node on GUI recursively
public void DrawOnGUIRecursively( string linkToPrevNodeDescription = null )
{
GUILayout.BeginHorizontal();
DrawOnGUI( linkToPrevNodeDescription );
if( links.Count > 0 )
{
GUILayout.BeginVertical();
for( int i = 0; i < links.Count; i++ )
{
ReferenceNode next = links[i].targetNode;
next.DrawOnGUIRecursively( links[i].description );
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
}
// Draw only this node on GUI
public void DrawOnGUI( string linkToPrevNodeDescription )
{
string label = GetNodeContent( linkToPrevNodeDescription );
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;
}
// Serialize this node and its connected nodes recursively
public int SerializeRecursively( Dictionary<ReferenceNode, int> nodeToIndex, List<ReferenceHolder.SerializableNode> serializedNodes )
{
int index;
if( nodeToIndex.TryGetValue( this, out index ) )
return index;
ReferenceHolder.SerializableNode serializedNode = new ReferenceHolder.SerializableNode()
{
instanceId = instanceId ?? 0,
isUnityObject = instanceId.HasValue,
description = description
};
index = serializedNodes.Count;
nodeToIndex[this] = index;
serializedNodes.Add( serializedNode );
if( links.Count > 0 )
{
serializedNode.links = new List<int>( links.Count );
serializedNode.linkDescriptions = new List<string>( links.Count );
for( int i = 0; i < links.Count; i++ )
{
serializedNode.links.Add( links[i].targetNode.SerializeRecursively( nodeToIndex, serializedNodes ) );
serializedNode.linkDescriptions.Add( links[i].description );
}
}
return index;
}
// Deserialize this node and its links from the serialized data
public void Deserialize( ReferenceHolder.SerializableNode serializedNode, List<ReferenceNode> allNodes )
{
if( serializedNode.isUnityObject )
instanceId = serializedNode.instanceId;
else
instanceId = null;
description = serializedNode.description;
if( serializedNode.links != null )
{
for( int i = 0; i < serializedNode.links.Count; i++ )
links.Add( new Link( allNodes[serializedNode.links[i]], serializedNode.linkDescriptions[i] ) );
}
}
public override int GetHashCode()
{
return uid;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca236e4f3c5a9f447be89f0e61e485fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,273 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
public static class Utilities
{
// A set of commonly used Unity types
private static readonly HashSet<Type> primitiveUnityTypes = new HashSet<Type>() {
typeof( string ), typeof( Vector4 ), typeof( Vector3 ), typeof( Vector2 ), typeof( Rect ),
typeof( Quaternion ), typeof( Color ), typeof( Color32 ), typeof( LayerMask ),
typeof( Matrix4x4 ), typeof( AnimationCurve ), typeof( Gradient ), typeof( RectOffset ) };
public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true );
public static readonly GUILayoutOption GL_EXPAND_HEIGHT = GUILayout.ExpandHeight( true );
public static readonly GUILayoutOption GL_WIDTH_25 = GUILayout.Width( 25 );
public static readonly GUILayoutOption GL_WIDTH_100 = GUILayout.Width( 100 );
public static readonly GUILayoutOption GL_WIDTH_250 = GUILayout.Width( 250 );
public static readonly GUILayoutOption GL_HEIGHT_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
{
get
{
if( m_boxGUIStyle == null )
{
m_boxGUIStyle = new GUIStyle( EditorStyles.helpBox )
{
alignment = TextAnchor.MiddleCenter,
font = EditorStyles.label.font
};
}
return m_boxGUIStyle;
}
}
private static GUIStyle m_tooltipGUIStyle; // GUIStyle used to draw the tooltip
public static GUIStyle TooltipGUIStyle
{
get
{
GUIStyleState normalState;
if( m_tooltipGUIStyle != null )
normalState = m_tooltipGUIStyle.normal;
else
{
m_tooltipGUIStyle = new GUIStyle( EditorStyles.helpBox )
{
alignment = TextAnchor.MiddleCenter,
font = EditorStyles.label.font
};
normalState = m_tooltipGUIStyle.normal;
normalState.background = null;
normalState.textColor = Color.black;
}
if( normalState.background == null || normalState.background.Equals( null ) )
{
Texture2D backgroundTexture = new Texture2D( 1, 1 );
backgroundTexture.SetPixel( 0, 0, new Color( 0.88f, 0.88f, 0.88f, 0.85f ) );
backgroundTexture.Apply();
normalState.background = backgroundTexture;
}
return m_tooltipGUIStyle;
}
}
// Get a unique-ish string hash code for an object
public static string Hash( this object obj )
{
if( obj is Object )
return obj.GetHashCode().ToString();
return obj.GetHashCode() + obj.GetType().Name;
}
// Check if object is an asset or a Scene object
public static bool IsAsset( this object obj )
{
return obj is Object && AssetDatabase.Contains( (Object) obj );
}
// Select an object in the editor
public static void SelectInEditor( this Object obj )
{
if( obj == null )
return;
Event e = Event.current;
// If CTRL key is pressed, do a multi-select;
// otherwise select only the clicked object and ping it in editor
if( !e.control )
{
obj.PingInEditor();
Selection.activeObject = obj;
}
else
{
Component objAsComp = obj as Component;
GameObject objAsGO = obj as GameObject;
int selectionIndex = -1;
Object[] selection = Selection.objects;
for( int i = 0; i < selection.Length; i++ )
{
Object selected = selection[i];
// Don't allow including both a gameobject and one of its components in the selection
if( selected == obj || ( objAsComp != null && selected == objAsComp.gameObject ) ||
( objAsGO != null && selected is Component && ( (Component) selected ).gameObject == objAsGO ) )
{
selectionIndex = i;
break;
}
}
Object[] newSelection;
if( selectionIndex == -1 )
{
// Include object in selection
newSelection = new Object[selection.Length + 1];
selection.CopyTo( newSelection, 0 );
newSelection[selection.Length] = obj;
}
else
{
// Remove object from selection
newSelection = new Object[selection.Length - 1];
int j = 0;
for( int i = 0; i < selectionIndex; i++, j++ )
newSelection[j] = selection[i];
for( int i = selectionIndex + 1; i < selection.Length; i++, j++ )
newSelection[j] = selection[i];
}
Selection.objects = newSelection;
}
}
// Ping an object in either Project view or Hierarchy view
public static void PingInEditor( this Object obj )
{
if( obj is Component )
obj = ( (Component) obj ).gameObject;
// Pinging a prefab only works if the pinged object is the root of the prefab
// or a direct child of it. Pinging any grandchildren of the prefab
// does not work; in which case, traverse the parent hierarchy until
// a pingable parent is reached
if( obj.IsAsset() && obj is GameObject )
{
#if UNITY_2018_3_OR_NEWER
Transform objTR = ( (GameObject) obj ).transform.root;
#else
Transform objTR = ( (GameObject) obj ).transform;
while( objTR.parent != null && objTR.parent.parent != null )
objTR = objTR.parent;
#endif
obj = objTR.gameObject;
}
EditorGUIUtility.PingObject( obj );
}
// Check if the field is serializable
public static bool IsSerializable( this FieldInfo fieldInfo )
{
// see Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( fieldInfo.IsInitOnly || ( ( !fieldInfo.IsPublic || fieldInfo.IsNotSerialized ) &&
!Attribute.IsDefined( fieldInfo, typeof( SerializeField ) ) ) )
return false;
return IsTypeSerializable( fieldInfo.FieldType );
}
// Check if the property is serializable
public static bool IsSerializable( this PropertyInfo propertyInfo )
{
return IsTypeSerializable( propertyInfo.PropertyType );
}
// Check if type is serializable
private static bool IsTypeSerializable( Type type )
{
// see Serialization Rules: https://docs.unity3d.com/Manual/script-Serialization.html
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
if( type.IsArray )
{
if( type.GetArrayRank() != 1 )
return false;
type = type.GetElementType();
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
else if( type.IsGenericType )
{
if( type.GetGenericTypeDefinition() != typeof( List<> ) )
return false;
type = type.GetGenericArguments()[0];
if( typeof( Object ).IsAssignableFrom( type ) )
return true;
}
if( type.IsGenericType )
return false;
return Attribute.IsDefined( type, typeof( SerializableAttribute ), false );
}
// Check if the type is a common Unity type (let's call them primitives)
public static bool IsPrimitiveUnityType( this Type type )
{
return type.IsPrimitive || primitiveUnityTypes.Contains( type );
}
// Get <get> function for a field
public static VariableGetVal CreateGetter( this FieldInfo fieldInfo, Type type )
{
// Commented the IL generator code below because it might actually be slower than simply using reflection
// Credit: https://www.codeproject.com/Articles/14560/Fast-Dynamic-Property-Field-Accessors
//DynamicMethod dm = new DynamicMethod( "Get" + fieldInfo.Name, fieldInfo.FieldType, new Type[] { typeof( object ) }, type );
//ILGenerator il = dm.GetILGenerator();
//// Load the instance of the object (argument 0) onto the stack
//il.Emit( OpCodes.Ldarg_0 );
//// Load the value of the object's field (fi) onto the stack
//il.Emit( OpCodes.Ldfld, fieldInfo );
//// return the value on the top of the stack
//il.Emit( OpCodes.Ret );
//return (VariableGetVal) dm.CreateDelegate( typeof( VariableGetVal ) );
return fieldInfo.GetValue;
}
// Get <get> function for a property
public static VariableGetVal CreateGetter( this PropertyInfo propertyInfo )
{
// Ignore indexer properties
if( propertyInfo.GetIndexParameters().Length > 0 )
return null;
MethodInfo mi = propertyInfo.GetGetMethod( true );
if( mi != null )
{
Type GenType = typeof( PropertyWrapper<,> ).MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType );
return ( (IPropertyAccessor) Activator.CreateInstance( GenType, mi ) ).GetValue;
}
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 52b272b7591fb90499916205261524e0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,69 @@
using System;
using System.Reflection;
namespace AssetUsageDetectorNamespace
{
// Delegate to get the value of a variable (either field or property)
public delegate object VariableGetVal( object obj );
// Custom struct to hold a variable, its important properties and its getter function
public struct VariableGetterHolder
{
public readonly string name;
public readonly bool isProperty;
public readonly bool isSerializable;
private readonly VariableGetVal getter;
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
{
name = fieldInfo.Name;
isProperty = false;
this.isSerializable = isSerializable;
this.getter = getter;
}
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
{
name = propertyInfo.Name;
isProperty = true;
this.isSerializable = isSerializable;
this.getter = getter;
}
public object Get( object obj )
{
return getter( obj );
}
}
// Credit: http://stackoverflow.com/questions/724143/how-do-i-create-a-delegate-for-a-net-property
public interface IPropertyAccessor
{
object GetValue( object source );
}
// A wrapper class for properties to get their values more efficiently
public class PropertyWrapper<TObject, TValue> : IPropertyAccessor where TObject : class
{
private readonly Func<TObject, TValue> getter;
public PropertyWrapper( MethodInfo getterMethod )
{
getter = (Func<TObject, TValue>) Delegate.CreateDelegate( typeof( Func<TObject, TValue> ), getterMethod );
}
public object GetValue( object obj )
{
try
{
return getter( (TObject) obj );
}
catch
{
// Property getters may return various kinds of exceptions
// if their backing fields are not initialized (yet)
return null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9e94c83e8b850514ca0217aeff1491a6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+15
View File
@@ -0,0 +1,15 @@
= Asset Usage Detector =
Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector
E-mail: yasirkula@gmail.com
1. ABOUT
This tool helps you find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. lists the objects that refer to them.
2. HOW TO
Simply open Window-Asset Usage Detector, select some assets, tweak the settings and GO!
3. KNOWN LIMITATIONS
- static variables are not searched
- GUIText materials are not searched
- Textures in Lens Flare's can not be searched
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ac528f1751f33a647a45caeff6a9344b
timeCreated: 1520032521
licenseType: Store
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant: