(Experimental)(#14) Added SearchRefactoring parameter to AssetUsageDetector (only useful while triggering the search via Scripting API). It allows getting notified of found references during the search (some references like Assembly Definition File references or Shader Graph references aren't supported) and in most cases, refactoring them (e.g. changing all usages of a searched object with something else or null). Disabling "Lazy Scene Search" is recommended while using this feature and it's advised to backup your project beforehand

This commit is contained in:
yasirkula
2022-01-05 10:18:17 +03:00
parent 8a6fe822d6
commit 4b146280ab
8 changed files with 690 additions and 47 deletions
+27
View File
@@ -37,6 +37,33 @@ There are 5 ways to install this plugin:
![SearchResults2](Images/SearchResults2Dark.png)
## SEARCH REFACTORING
While searching for references using the Scripting API, it's possible to get notified of the found references *during* the search (some references like *Assembly Definition File* references or *Shader Graph* references aren't supported) and in most cases, refactor them (e.g. changing all usages of a searched object with something else or *null*). Disabling *Lazy Scene Search* is recommended while using this feature and it's advised to backup your project beforehand.
To initiate a search using the Scripting API, you need to put your script either in *Editor* folder or add `AssetUsageDetector.Editor` as reference to your *Assembly Definition File*. Then, you can either create a new instance of `AssetUsageDetectorNamespace.AssetUsageDetector` object and call its `Run` method, or call the `AssetUsageDetectorNamespace.AssetUsageDetectorWindow.ShowAndSearch` method. In either case, you'll be handling the search refactoring in the **searchRefactoring** callback:
```csharp
void ReplaceFontUsages( Font from, Font to )
{
AssetUsageDetector assetUsageDetector = new AssetUsageDetector();
assetUsageDetector.Run( new AssetUsageDetector.Parameters()
{
objectsToSearch = new Object[] { from },
lazySceneSearch = false,
searchRefactoring = ( searchMatch ) =>
{
Debug.LogFormat( "Found a {0} reference from {1} to {2}", searchMatch.GetType().Name, searchMatch.Source, searchMatch.Value );
searchMatch.ChangeValue( to );
}
} );
}
```
**NOTE:** Refactored references won't be reflected to the returned search results, old references will continue to be displayed. After saving the changes (modified scenes) and initiating another search, correct search results will be shown.
**NOTE2:** After refactoring the references, consider performing a normal search to see if all references were correctly refactored. If some references weren't refactored (even though they could've been), feel free to report it.
## KNOWN LIMITATIONS
- *Addressables* aren't supported
@@ -44,6 +44,8 @@ namespace AssetUsageDetectorNamespace
public bool searchUnusedMaterialProperties = true;
public SearchRefactoring searchRefactoring = null;
public bool lazySceneSearch = true;
public bool calculateUnusedObjects = false;
public bool hideDuplicateRows = true;
@@ -53,6 +55,8 @@ namespace AssetUsageDetectorNamespace
}
#endregion
private Parameters searchParameters;
// A set that contains the searched scene object(s), asset(s) and their sub-assets (if any)
private readonly HashSet<Object> objectsToSearchSet = new HashSet<Object>();
// Scenes of scene object(s) in objectsToSearchSet
@@ -78,14 +82,9 @@ namespace AssetUsageDetectorNamespace
// Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function)
private readonly List<object> callStack = new List<object>( 64 );
private int searchDepthLimit; // Depth limit for recursively searching variables of objects
private Object currentSearchedObject;
private int currentDepth;
private bool searchUnusedMaterialProperties;
private bool dontSearchInSourceAssets;
private bool searchingSourceAssets;
private bool isInPlayMode;
@@ -166,6 +165,8 @@ namespace AssetUsageDetectorNamespace
try
{
this.searchParameters = searchParameters;
// Initialize commonly used variables
searchResult = new List<SearchResultGroup>(); // Overall search results
@@ -174,10 +175,6 @@ namespace AssetUsageDetectorNamespace
searchedObjectsCount = 0;
searchStartTime = EditorApplication.timeSinceStartup;
searchDepthLimit = searchParameters.searchDepthLimit;
dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchedObjects.Clear();
searchedUnityObjects.Clear();
animationClipUniqueBindings.Clear();
@@ -545,7 +542,7 @@ namespace AssetUsageDetectorNamespace
}
// Searching source assets last prevents some references from being excluded due to callStack.ContainsFast
if( !dontSearchInSourceAssets )
if( !searchParameters.dontSearchInSourceAssets )
{
searchingSourceAssets = true;
@@ -833,7 +830,7 @@ namespace AssetUsageDetectorNamespace
if( !string.IsNullOrEmpty( assetPath ) )
{
assetsToSearchPathsSet.Add( assetPath );
if( dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
if( searchParameters.dontSearchInSourceAssets && AssetDatabase.IsMainAsset( obj ) )
excludedAssetsPathsSet.Add( assetPath );
}
@@ -1062,7 +1059,7 @@ namespace AssetUsageDetectorNamespace
else
{
// Comply with the recursive search limit
if( currentDepth >= searchDepthLimit )
if( currentDepth >= searchParameters.searchDepthLimit )
return null;
callStack.Add( obj );
@@ -358,13 +358,18 @@ namespace AssetUsageDetectorNamespace
#if UNITY_2018_3_OR_NEWER
Object prefab = go;
while( prefab = PrefabUtility.GetCorrespondingObjectFromSource( prefab ) )
#else
Object prefab = PrefabUtility.GetPrefabParent( go );
if( prefab )
#endif
{
#if !UNITY_2018_3_OR_NEWER
Object prefab = PrefabUtility.GetPrefabParent( go );
#endif
if( objectsToSearchSet.Contains( prefab ) && assetsToSearchRootPrefabs.ContainsFast( prefab as GameObject ) )
{
referenceNode.AddLinkTo( GetReferenceNode( prefab ), "Prefab object" );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new PrefabMatch( go, prefab ) );
}
}
}
@@ -392,14 +397,43 @@ namespace AssetUsageDetectorNamespace
// Although SearchVariablesWithSerializedObject can detect these references with SerializedObject, it isn't possible when reflection is used in Play mode
MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component );
if( objectsToSearchSet.Contains( script ) )
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( component.gameObject, script, component ) );
}
}
if( component is Animation )
{
// Search animation clips for references
foreach( AnimationState anim in (Animation) component )
referenceNode.AddLinkTo( SearchObject( anim.clip ) );
if( searchParameters.searchRefactoring == null )
{
foreach( AnimationState anim in (Animation) component )
referenceNode.AddLinkTo( SearchObject( anim.clip ) );
}
else
{
AnimationClip[] clips = AnimationUtility.GetAnimationClips( component.gameObject );
bool modifiedClips = false;
for( int i = 0; i < clips.Length; i++ )
{
referenceNode.AddLinkTo( SearchObject( clips[i] ) );
if( objectsToSearchSet.Contains( clips[i] ) )
{
searchParameters.searchRefactoring( new AnimationSystemMatch( component, clips[i], ( newValue ) =>
{
clips[i] = (AnimationClip) newValue;
modifiedClips = true;
} ) );
}
}
if( modifiedClips )
AnimationUtility.SetAnimationClips( (Animation) component, clips );
}
// Search the objects that are animated by this Animation component for references
SearchAnimatedObjects( referenceNode );
@@ -407,7 +441,11 @@ namespace AssetUsageDetectorNamespace
else if( component is Animator )
{
// Search animation clips for references (via AnimatorController)
referenceNode.AddLinkTo( SearchObject( ( (Animator) component ).runtimeAnimatorController ) );
RuntimeAnimatorController animatorController = ( (Animator) component ).runtimeAnimatorController;
referenceNode.AddLinkTo( SearchObject( animatorController ) );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( animatorController ) )
searchParameters.searchRefactoring( new AnimationSystemMatch( component, animatorController, ( newValue ) => ( (Animator) component ).runtimeAnimatorController = (RuntimeAnimatorController) newValue ) );
// Search the objects that are animated by this Animator component for references
SearchAnimatedObjects( referenceNode );
@@ -422,7 +460,12 @@ namespace AssetUsageDetectorNamespace
if( tiles != null )
{
for( int i = 0; i < tiles.Length; i++ )
{
referenceNode.AddLinkTo( SearchObject( tiles[i] ), "Tile" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( tiles[i] ) )
searchParameters.searchRefactoring( new OtherSearchMatch( component, tiles[i], ( newValue ) => ( (Tilemap) component ).SwapTile( tiles[i], (TileBase) newValue ) ) );
}
}
}
#endif
@@ -434,7 +477,13 @@ namespace AssetUsageDetectorNamespace
if( playableAsset != null && !playableAsset.Equals( null ) )
{
foreach( PlayableBinding binding in playableAsset.outputs )
referenceNode.AddLinkTo( SearchObject( ( (PlayableDirector) component ).GetGenericBinding( binding.sourceObject ) ), "Binding: " + binding.streamName );
{
Object bindingValue = ( (PlayableDirector) component ).GetGenericBinding( binding.sourceObject );
referenceNode.AddLinkTo( SearchObject( bindingValue ), "Binding: " + binding.streamName );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( bindingValue ) )
searchParameters.searchRefactoring( new AnimationSystemMatch( component, bindingValue, ( newValue ) => ( (PlayableDirector) component ).SetGenericBinding( binding.sourceObject, newValue ) ) );
}
}
}
#endif
@@ -445,8 +494,23 @@ namespace AssetUsageDetectorNamespace
{
Mesh[] meshes = new Mesh[( (ParticleSystemRenderer) component ).meshCount];
int meshCount = ( (ParticleSystemRenderer) component ).GetMeshes( meshes );
bool modifiedMeshes = false;
for( int i = 0; i < meshCount; i++ )
{
referenceNode.AddLinkTo( SearchObject( meshes[i] ), "Renderer Module: Mesh" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( meshes[i] ) )
{
searchParameters.searchRefactoring( new OtherSearchMatch( component, meshes[i], ( newValue ) =>
{
meshes[i] = (Mesh) newValue;
modifiedMeshes = true;
} ) );
}
}
if( modifiedMeshes )
( (ParticleSystemRenderer) component ).SetMeshes( meshes, meshCount );
}
}
else if( component is ParticleSystem )
@@ -467,6 +531,9 @@ namespace AssetUsageDetectorNamespace
{
Transform plane = collisionModule.GetPlane( i );
referenceNode.AddLinkTo( SearchObject( plane ), "Collision Module: Plane" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( plane ) )
searchParameters.searchRefactoring( new OtherSearchMatch( collisionModule, plane, component, ( newValue ) => collisionModule.SetPlane( i, (Transform) newValue ) ) );
}
}
catch { }
@@ -482,6 +549,9 @@ namespace AssetUsageDetectorNamespace
{
Component collider = triggerModule.GetCollider( i );
referenceNode.AddLinkTo( SearchObject( collider ), "Trigger Module: Collider" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( collider ) )
searchParameters.searchRefactoring( new OtherSearchMatch( triggerModule, collider, component, ( newValue ) => triggerModule.SetCollider( i, (Component) newValue ) ) );
}
}
catch { }
@@ -494,6 +564,9 @@ namespace AssetUsageDetectorNamespace
{
Sprite sprite = textureSheetAnimationModule.GetSprite( i );
referenceNode.AddLinkTo( SearchObject( sprite ), "Texture Sheet Animation Module: Sprite" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( sprite ) )
searchParameters.searchRefactoring( new OtherSearchMatch( textureSheetAnimationModule, sprite, component, ( newValue ) => textureSheetAnimationModule.SetSprite( i, (Sprite) newValue ) ) );
}
}
catch { }
@@ -507,6 +580,9 @@ namespace AssetUsageDetectorNamespace
{
ParticleSystem subEmitterSystem = subEmittersModule.GetSubEmitterSystem( i );
referenceNode.AddLinkTo( SearchObject( subEmitterSystem ), "Sub Emitters Module: ParticleSystem" );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( subEmitterSystem ) )
searchParameters.searchRefactoring( new OtherSearchMatch( subEmittersModule, subEmitterSystem, component, ( newValue ) => subEmittersModule.SetSubEmitterSystem( i, (ParticleSystem) newValue ) ) );
}
}
catch { }
@@ -554,7 +630,7 @@ namespace AssetUsageDetectorNamespace
string propertyName = materialSO.FindProperty( "m_SavedProperties.m_TexEnvs.Array.data[" + texturePropertyIndex + "].first" ).stringValue;
if( material.HasProperty( propertyName ) )
linkDescriptions[j] = "[Property: " + propertyName + "]";
else if( searchUnusedMaterialProperties )
else if( searchParameters.searchUnusedMaterialProperties )
{
// Move unused references to the end of the list so that used references come first
linkDescriptions.Add( "[Property (UNUSED): " + propertyName + "]" );
@@ -583,7 +659,12 @@ namespace AssetUsageDetectorNamespace
string propertyName = ShaderUtil.GetPropertyName( shader, i );
Texture assignedTexture = material.GetTexture( propertyName );
if( objectsToSearchSet.Contains( assignedTexture ) )
{
referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new OtherSearchMatch( material, assignedTexture, ( newValue ) => material.SetTexture( propertyName, (Texture) newValue ) ) );
}
}
}
}
@@ -615,7 +696,12 @@ namespace AssetUsageDetectorNamespace
#endif
if( objectsToSearchSet.Contains( defaultTexture ) )
{
referenceNode.AddLinkTo( GetReferenceNode( defaultTexture ), "Default Texture: " + propertyName );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new AssetImporterDefaultValueMatch( shaderImporter, defaultTexture, propertyName, null ) );
}
}
}
}
@@ -662,11 +748,16 @@ namespace AssetUsageDetectorNamespace
VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType );
for( int i = 0; i < variables.Length; i++ )
{
if( variables[i].isSerializable && !variables[i].isProperty )
if( variables[i].isSerializable && !variables[i].IsProperty )
{
Object defaultValue = scriptImporter.GetDefaultReference( variables[i].name );
Object defaultValue = scriptImporter.GetDefaultReference( variables[i].Name );
if( objectsToSearchSet.Contains( defaultValue ) )
referenceNode.AddLinkTo( GetReferenceNode( defaultValue ), "Default variable value: " + variables[i].name );
{
referenceNode.AddLinkTo( GetReferenceNode( defaultValue ), "Default variable value: " + variables[i].Name );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new AssetImporterDefaultValueMatch( scriptImporter, defaultValue, variables[i].Name, variables ) );
}
}
}
}
@@ -685,8 +776,13 @@ namespace AssetUsageDetectorNamespace
for( int i = 0; i < layers.Length; i++ )
{
if( objectsToSearchSet.Contains( layers[i].avatarMask ) )
{
referenceNode.AddLinkTo( GetReferenceNode( layers[i].avatarMask ), layers[i].name + " Mask" );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new AnimationSystemMatch( layers[i], layers[i].avatarMask, controller, ( newValue ) => layers[i].avatarMask = (AvatarMask) newValue ) );
}
referenceNode.AddLinkTo( SearchObject( layers[i].stateMachine ) );
}
}
@@ -696,7 +792,33 @@ namespace AssetUsageDetectorNamespace
{
RuntimeAnimatorController parentController = ( (AnimatorOverrideController) controller ).runtimeAnimatorController;
if( objectsToSearchSet.Contains( parentController ) )
{
referenceNode.AddLinkTo( GetReferenceNode( parentController ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new AnimationSystemMatch( controller, parentController, ( newValue ) => ( (AnimatorOverrideController) controller ).runtimeAnimatorController = (RuntimeAnimatorController) newValue ) );
}
if( searchParameters.searchRefactoring != null )
{
List<KeyValuePair<AnimationClip, AnimationClip>> overrideClips = new List<KeyValuePair<AnimationClip, AnimationClip>>( ( (AnimatorOverrideController) controller ).overridesCount );
( (AnimatorOverrideController) controller ).GetOverrides( overrideClips );
bool modifiedOverrideClips = false;
for( int i = overrideClips.Count - 1; i >= 0; i-- )
{
if( objectsToSearchSet.Contains( overrideClips[i].Value ) )
{
searchParameters.searchRefactoring( new AnimationSystemMatch( controller, overrideClips[i].Value, ( newValue ) =>
{
overrideClips[i] = new KeyValuePair<AnimationClip, AnimationClip>( overrideClips[i].Key, (AnimationClip) newValue );
modifiedOverrideClips = true;
} ) );
}
}
if( modifiedOverrideClips )
( (AnimatorOverrideController) controller ).ApplyOverrides( overrideClips );
}
}
AnimationClip[] animClips = controller.animationClips;
@@ -727,7 +849,12 @@ namespace AssetUsageDetectorNamespace
{
MonoScript script = MonoScript.FromScriptableObject( behaviours[i] );
if( objectsToSearchSet.Contains( script ) )
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( animatorStateMachine, script, behaviours[i] ) );
}
}
}
@@ -741,6 +868,9 @@ namespace AssetUsageDetectorNamespace
referenceNode.AddLinkTo( SearchObject( animatorState.motion ), "Motion" );
if( searchParameters.searchRefactoring != null && animatorState.motion as AnimationClip && objectsToSearchSet.Contains( animatorState.motion ) )
searchParameters.searchRefactoring( new AnimationSystemMatch( animatorState, animatorState.motion, ( newValue ) => animatorState.motion = (Motion) newValue ) );
if( searchMonoBehavioursForScript )
{
StateMachineBehaviour[] behaviours = animatorState.behaviours;
@@ -748,7 +878,12 @@ namespace AssetUsageDetectorNamespace
{
MonoScript script = MonoScript.FromScriptableObject( behaviours[i] );
if( objectsToSearchSet.Contains( script ) )
{
referenceNode.AddLinkTo( GetReferenceNode( script ) );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new BehaviourUsageMatch( animatorState, script, behaviours[i] ) );
}
}
}
@@ -768,8 +903,13 @@ namespace AssetUsageDetectorNamespace
ChildMotion[] children = blendTree.children;
for( int i = 0; i < children.Length; i++ )
{
referenceNode.AddLinkTo( SearchObject( children[i].motion ), "Motion" );
if( searchParameters.searchRefactoring != null && children[i].motion as AnimationClip && objectsToSearchSet.Contains( children[i].motion ) )
searchParameters.searchRefactoring( new AnimationSystemMatch( blendTree, children[i].motion, ( newValue ) => children[i].motion = (Motion) newValue ) );
}
return referenceNode;
}
@@ -784,15 +924,45 @@ namespace AssetUsageDetectorNamespace
{
// Search through all the keyframes in this curve
ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve( clip, objectCurves[i] );
bool modifiedKeyframes = false;
for( int j = 0; j < keyframes.Length; j++ )
{
referenceNode.AddLinkTo( SearchObject( keyframes[j].value ), "Keyframe: " + keyframes[j].time );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( keyframes[j].value ) )
{
searchParameters.searchRefactoring( new AnimationSystemMatch( clip, keyframes[j].value, ( newValue ) =>
{
keyframes[j].value = newValue;
modifiedKeyframes = true;
} ) );
}
}
if( modifiedKeyframes )
AnimationUtility.SetObjectReferenceCurve( clip, objectCurves[i], keyframes );
}
// Get all events from animation clip
AnimationEvent[] events = AnimationUtility.GetAnimationEvents( clip );
bool modifiedEvents = false;
for( int i = 0; i < events.Length; i++ )
{
referenceNode.AddLinkTo( SearchObject( events[i].objectReferenceParameter ), "AnimationEvent: " + events[i].time );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( events[i].objectReferenceParameter ) )
{
searchParameters.searchRefactoring( new AnimationSystemMatch( clip, events[i].objectReferenceParameter, ( newValue ) =>
{
events[i].objectReferenceParameter = newValue;
modifiedEvents = true;
} ) );
}
}
if( modifiedEvents )
AnimationUtility.SetAnimationEvents( clip, events );
return referenceNode;
}
@@ -805,24 +975,39 @@ namespace AssetUsageDetectorNamespace
SerializedObject spriteAtlasSO = new SerializedObject( spriteAtlas );
if( spriteAtlas.isVariant )
{
Object masterAtlas = spriteAtlasSO.FindProperty( "m_MasterAtlas" ).objectReferenceValue;
SerializedProperty masterAtlasProperty = spriteAtlasSO.FindProperty( "m_MasterAtlas" );
Object masterAtlas = masterAtlasProperty.objectReferenceValue;
if( objectsToSearchSet.Contains( masterAtlas ) )
{
referenceNode.AddLinkTo( SearchObject( masterAtlas ), "Master Atlas" );
if( searchParameters.searchRefactoring != null )
searchParameters.searchRefactoring( new SerializedPropertyMatch( spriteAtlas, masterAtlas, masterAtlasProperty ) );
}
}
#if UNITY_2018_2_OR_NEWER
Object[] packables = spriteAtlas.GetPackables();
if( packables != null )
{
for( int i = 0; i < packables.Length; i++ )
SearchSpriteAtlas( referenceNode, packables[i] );
}
#else
SerializedProperty packables = spriteAtlasSO.FindProperty( "m_EditorData.packables" );
if( packables != null )
{
for( int i = 0, length = packables.arraySize; i < length; i++ )
SearchSpriteAtlas( referenceNode, packables.GetArrayElementAtIndex( i ).objectReferenceValue );
{
SerializedProperty packedSpriteProperty = packables.GetArrayElementAtIndex( i );
Object packedSprite = packedSpriteProperty.objectReferenceValue;
SearchSpriteAtlas( referenceNode, packedSprite );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( packedSprite ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( spriteAtlas, packedSprite, packedSpriteProperty ) );
}
}
#if UNITY_2018_2_OR_NEWER
else
{
Object[] _packables = spriteAtlas.GetPackables();
if( _packables != null )
{
for( int i = 0; i < _packables.Length; i++ )
SearchSpriteAtlas( referenceNode, _packables[i] );
}
}
#endif
@@ -1188,28 +1373,34 @@ namespace AssetUsageDetectorNamespace
continue;
}
Object propertyValue;
ReferenceNode searchResult;
switch( iterator.propertyType )
{
case SerializedPropertyType.ObjectReference:
searchResult = SearchObject( PreferablyGameObject( iterator.objectReferenceValue ) );
propertyValue = iterator.objectReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
case SerializedPropertyType.ExposedReference:
searchResult = SearchObject( PreferablyGameObject( iterator.exposedReferenceValue ) );
propertyValue = iterator.exposedReferenceValue;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference:
searchResult = SearchObject( PreferablyGameObject( GetRawSerializedPropertyValue( iterator ) ) );
propertyValue = GetRawSerializedPropertyValue( iterator ) as Object;
searchResult = SearchObject( PreferablyGameObject( propertyValue ) );
enterChildren = false;
break;
#endif
case SerializedPropertyType.Generic:
propertyValue = null;
searchResult = null;
enterChildren = true;
break;
default:
propertyValue = null;
searchResult = null;
enterChildren = false;
break;
@@ -1221,7 +1412,12 @@ namespace AssetUsageDetectorNamespace
// m_RD.texture is a redundant reference that shows up when searching sprites
if( !propertyPath.EndsWithFast( "m_RD.texture" ) )
{
referenceNode.AddLinkTo( searchResult, "Variable: " + propertyPath.Replace( ".Array.data[", "[" ) ); // "arrayVariable.Array.data[0]" becomes "arrayVariable[0]"
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( propertyValue ) )
searchParameters.searchRefactoring( new SerializedPropertyMatch( (Object) referenceNode.nodeObject, propertyValue, iterator ) );
}
}
} while( iterator.Next( enterChildren ) );
@@ -1256,7 +1452,12 @@ namespace AssetUsageDetectorNamespace
{
ReferenceNode searchResult = SearchObject( PreferablyGameObject( variableValue ) );
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, ( variables[i].isProperty ? "Property: " : "Variable: " ) + variables[i].name );
{
referenceNode.AddLinkTo( searchResult, ( variables[i].IsProperty ? "Property: " : "Variable: " ) + variables[i].Name );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( variableValue as Object ) )
searchParameters.searchRefactoring( new ReflectionMatch( referenceNode.nodeObject, (Object) variableValue, variables[i].variable ) );
}
}
if( variableValue is IEnumerable && !( variableValue is Transform ) )
@@ -1264,14 +1465,31 @@ namespace AssetUsageDetectorNamespace
// If the field is IEnumerable (possibly an array or collection), search through members of it
// Note that Transform IEnumerable (children of the transform) is not iterated
int index = 0;
List<Object> foundReferences = null;
foreach( object element in (IEnumerable) variableValue )
{
ReferenceNode searchResult = SearchObject( PreferablyGameObject( element ) );
if( searchResult != null && searchResult != referenceNode )
referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].isProperty ? "Property: " : "Variable: ", variables[i].name, "[", index + "]" ) );
{
referenceNode.AddLinkTo( searchResult, string.Concat( variables[i].IsProperty ? "Property: " : "Variable: ", variables[i].Name, "[", index + "]" ) );
if( searchParameters.searchRefactoring != null && objectsToSearchSet.Contains( element as Object ) )
{
if( foundReferences == null )
foundReferences = new List<Object>( 2 ) { (Object) element };
else if( !foundReferences.Contains( (Object) element ) )
foundReferences.Add( (Object) element );
}
}
index++;
}
if( foundReferences != null )
{
for( int j = foundReferences.Count - 1; j >= 0; j-- )
searchParameters.searchRefactoring( new ReflectionMatch( referenceNode.nodeObject, foundReferences[j], variableValue ) );
}
}
}
catch( UnassignedReferenceException ) { }
@@ -1285,7 +1503,7 @@ namespace AssetUsageDetectorNamespace
sb.Length = 0;
sb.EnsureCapacity( callStack.Count * 50 + 1000 );
sb.Append( "Skipped searching " ).Append( referenceNode.nodeObject.GetType().FullName ).Append( "." ).Append( variables[i].name ).AppendLine( " because it threw exception:" ).Append( e ).AppendLine();
sb.Append( "Skipped searching " ).Append( referenceNode.nodeObject.GetType().FullName ).Append( "." ).Append( variables[i].Name ).AppendLine( " because it threw exception:" ).Append( e ).AppendLine();
Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb );
Debug.LogWarning( sb.ToString(), latestUnityObjectInCallStack );
@@ -1430,7 +1648,7 @@ namespace AssetUsageDetectorNamespace
// Credit: http://answers.unity.com/answers/425602/view.html
// Returns the raw System.Object value of a SerializedProperty
public object GetRawSerializedPropertyValue( SerializedProperty property )
private object GetRawSerializedPropertyValue( SerializedProperty property )
{
object result = property.serializedObject.targetObject;
string[] path = property.propertyPath.Replace( ".Array.data[", "[" ).Split( '.' );
@@ -90,6 +90,8 @@ namespace AssetUsageDetectorNamespace
private BindingFlags fieldModifiers, propertyModifiers;
private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch
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 );
@@ -304,6 +306,7 @@ namespace AssetUsageDetectorNamespace
propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch;
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows;
@@ -666,6 +669,7 @@ namespace AssetUsageDetectorNamespace
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
lazySceneSearch = lazySceneSearch,
calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows,
@@ -676,6 +680,9 @@ namespace AssetUsageDetectorNamespace
currentPhase = Phase.Complete;
// We really don't want SearchRefactoring to affect next searches unless the search is initiated via ShowAndSearch again
searchRefactoring = null;
if( AssetUsageDetectorSettings.ShowCustomTooltip )
wantsMouseMove = wantsMouseEnterLeaveWindow = true;
}
@@ -0,0 +1,382 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using Object = UnityEngine.Object;
namespace AssetUsageDetectorNamespace
{
public delegate void SearchRefactoring( SearchMatch match );
public abstract class SearchMatch
{
public readonly object Source;
public readonly Object Context; // Almost always equal to Source. This is the Object that needs to be dirtied (if not null) to notify Unity of changes to Value
public Object Value { get; private set; }
protected SearchMatch( object source, Object value )
{
Source = source;
Context = source as Object;
Value = value;
}
protected SearchMatch( object source, Object value, Object context ) : this( source, value )
{
Context = context;
}
public void ChangeValue( Object newValue )
{
if( newValue == Value )
return;
if( Context && ( Context.hideFlags & HideFlags.NotEditable ) == HideFlags.NotEditable )
{
Debug.LogWarning( "Can't change value of read-only Object: " + Context, Context );
return;
}
try
{
bool setContextDirty;
if( ChangeValue( newValue, out setContextDirty ) )
OnValueChanged( newValue, setContextDirty );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
protected abstract bool ChangeValue( Object newValue, out bool setContextDirty );
public void OnValueChanged( Object newValue, bool setContextDirty = true )
{
Value = newValue;
if( setContextDirty )
{
if( Context )
{
if( AssetDatabase.Contains( Context ) )
EditorUtility.SetDirty( Context );
else if( !EditorApplication.isPlaying )
{
EditorUtility.SetDirty( Context );
if( Context is Component )
EditorSceneManager.MarkSceneDirty( ( (Component) Context ).gameObject.scene );
else if( Context is GameObject )
EditorSceneManager.MarkSceneDirty( ( (GameObject) Context ).scene );
else
EditorSceneManager.MarkAllScenesDirty();
}
}
else if( !EditorApplication.isPlaying )
EditorSceneManager.MarkAllScenesDirty();
}
}
}
public abstract class GenericSearchMatch : SearchMatch
{
public delegate void SetterFunction( Object newValue );
public readonly SetterFunction Setter;
internal GenericSearchMatch( object source, Object value, SetterFunction setter ) : base( source, value ) { Setter = setter; }
internal GenericSearchMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context ) { Setter = setter; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
Setter( newValue );
setContextDirty = true;
return true;
}
}
public abstract class ReadOnlySearchMatch : SearchMatch
{
internal ReadOnlySearchMatch( object source, Object value ) : base( source, value ) { }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
Debug.LogWarning( "Can't change value of " + GetType().Name );
setContextDirty = false;
return false;
}
}
/// <summary>
/// - Source: Object whose SerializedProperty points to Value
/// - Value: Referenced object
/// - SerializedProperty: The SerializedProperty that points to Value
/// </summary>
public class SerializedPropertyMatch : SearchMatch
{
public readonly SerializedProperty SerializedProperty; // Next or NextVisible mustn't be called with this SerializedProperty
internal SerializedPropertyMatch( Object source, Object value, SerializedProperty property ) : base( source, value ) { SerializedProperty = property; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = true;
switch( SerializedProperty.propertyType )
{
case SerializedPropertyType.ObjectReference:
SerializedProperty.objectReferenceValue = newValue;
if( SerializedProperty.objectReferenceValue != newValue )
{
Debug.LogWarning( "Couldn't cast " + newValue.GetType() + " to " + SerializedProperty.type );
SerializedProperty.objectReferenceValue = Value;
return false;
}
break;
case SerializedPropertyType.ExposedReference:
SerializedProperty.exposedReferenceValue = newValue;
if( SerializedProperty.exposedReferenceValue != newValue )
{
Debug.LogWarning( "Couldn't cast " + newValue.GetType() + " to " + SerializedProperty.type );
SerializedProperty.exposedReferenceValue = Value;
return false;
}
break;
#if UNITY_2019_3_OR_NEWER
case SerializedPropertyType.ManagedReference: SerializedProperty.managedReferenceValue = newValue; break;
#endif
}
SerializedProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo();
return true;
}
}
/// <summary>
/// - Source: Object whose variable points to Value
/// - Value: Referenced object
/// - Variable: FieldInfo, PropertyInfo or IEnumerable (ChangeValue may not work for all IEnumerables)
/// </summary>
public class ReflectionMatch : SearchMatch
{
public readonly object Variable;
internal ReflectionMatch( object source, Object value, object variable ) : base( source, value ) { Variable = variable; }
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = true;
if( Variable is FieldInfo )
( (FieldInfo) Variable ).SetValue( Source, newValue );
else if( Variable is PropertyInfo )
{
PropertyInfo property = (PropertyInfo) Variable;
if( !property.CanWrite )
{
Debug.LogWarning( "Property is read-only: " + property.DeclaringType.FullName + "." + property.Name );
return false;
}
property.SetValue( Source, newValue, null );
}
else if( Variable is IList )
{
IList list = (IList) Variable;
for( int i = list.Count - 1; i >= 0; i-- )
{
if( ReferenceEquals( list[i], Value ) )
list[i] = newValue;
}
}
else if( Variable is IDictionary )
{
IDictionary dictionary = (IDictionary) Variable;
bool dictionaryModified;
do
{
dictionaryModified = false;
foreach( object dictKey in dictionary.Keys )
{
object dictValue = dictionary[dictKey];
if( ReferenceEquals( dictKey, Value ) )
{
dictionary.Remove( dictKey );
if( newValue )
dictionary[newValue] = dictValue;
dictionaryModified = true;
break;
}
else if( ReferenceEquals( dictValue, Value ) )
{
dictionary[dictKey] = newValue;
dictionaryModified = true;
break;
}
}
} while( dictionaryModified );
}
else
{
Debug.LogWarning( "Can't change value of " + Variable.GetType().Name );
return false;
}
return true;
}
}
/// <summary>
/// - Source: MonoImporter (for scripts) or ShaderImporter
/// - Value: Default value assigned to Source's specified variable in the Inspector
/// - Variable: The variable of Source that Value is assigned to as default value
/// - MonoScriptAllVariables: All variables of Source script if it's MonoImporter
/// </summary>
public class AssetImporterDefaultValueMatch : SearchMatch
{
public readonly string Variable;
public readonly VariableGetterHolder[] MonoScriptAllVariables;
internal AssetImporterDefaultValueMatch( Object source, Object value, string variable, VariableGetterHolder[] monoScriptAllVariables ) : base( source, value )
{
Variable = variable;
MonoScriptAllVariables = monoScriptAllVariables;
}
protected override bool ChangeValue( Object newValue, out bool setContextDirty )
{
setContextDirty = false;
if( Source is MonoImporter )
{
MonoImporter monoImporter = (MonoImporter) Source;
List<string> variableNames = new List<string>( 8 );
List<Object> variableValues = new List<Object>( 8 );
for( int i = 0; i < MonoScriptAllVariables.Length; i++ )
{
if( MonoScriptAllVariables[i].isSerializable && !MonoScriptAllVariables[i].IsProperty )
{
Object variableDefaultValue = monoImporter.GetDefaultReference( MonoScriptAllVariables[i].Name );
if( variableDefaultValue == Value && MonoScriptAllVariables[i].Name == Variable )
variableDefaultValue = newValue;
variableNames.Add( MonoScriptAllVariables[i].Name );
variableValues.Add( variableDefaultValue );
}
}
monoImporter.SetDefaultReferences( variableNames.ToArray(), variableValues.ToArray() );
EditorApplication.delayCall += () => AssetDatabase.ImportAsset( monoImporter.assetPath ); // If code recompiles during search, it will break the search. Give it a 1 frame delay
}
else if( Source is ShaderImporter )
{
ShaderImporter shaderImporter = (ShaderImporter) Source;
Shader shader = shaderImporter.GetShader();
List<string> textureNames = new List<string>( 16 );
List<Texture> textureValues = new List<Texture>( 16 );
#if UNITY_2018_1_OR_NEWER
List<string> nonModifiableTextureNames = new List<string>( 16 );
List<Texture> nonModifiableTextureValues = new List<Texture>( 16 );
#endif
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
for( int i = 0; i < shaderPropertyCount; i++ )
{
if( ShaderUtil.GetPropertyType( shader, i ) != ShaderUtil.ShaderPropertyType.TexEnv )
continue;
string propertyName = ShaderUtil.GetPropertyName( shader, i );
#if UNITY_2018_1_OR_NEWER
if( ShaderUtil.IsShaderPropertyNonModifiableTexureProperty( shader, i ) )
{
Texture propertyDefaultValue = shaderImporter.GetNonModifiableTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable )
propertyDefaultValue = (Texture) newValue;
nonModifiableTextureNames.Add( propertyName );
nonModifiableTextureValues.Add( propertyDefaultValue );
}
else
#endif
{
Texture propertyDefaultValue = shaderImporter.GetDefaultTexture( propertyName );
if( propertyDefaultValue == Value && propertyName == Variable )
propertyDefaultValue = (Texture) newValue;
textureNames.Add( propertyName );
textureValues.Add( propertyDefaultValue );
}
}
shaderImporter.SetDefaultTextures( textureNames.ToArray(), textureValues.ToArray() );
#if UNITY_2018_1_OR_NEWER
shaderImporter.SetNonModifiableTextures( nonModifiableTextureNames.ToArray(), nonModifiableTextureValues.ToArray() );
#endif
AssetDatabase.ImportAsset( shaderImporter.assetPath );
}
else
{
Debug.LogWarning( "Can't change default value of: " + Source.GetType() );
return false;
}
return true;
}
}
/// <summary>
/// - Source: Animation, Animator, AnimatorStateMachine, AnimatorState, AnimatorControllerLayer, BlendTree, PlayableDirector* or AnimationClip*
/// - Context: If Source is AnimatorControllerLayer, then its RuntimeAnimatorController. Otherwise, equal to Source
/// - Value: AnimationClip, AnimatorController or AvatarMask used in Source (*for PlayableDirector and AnimationClip, it can be any Object value)
/// </summary>
public class AnimationSystemMatch : GenericSearchMatch
{
internal AnimationSystemMatch( object source, Object value, SetterFunction setter ) : base( source, value, setter ) { }
internal AnimationSystemMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context, setter ) { }
}
/// <summary>
/// - Source: GameObject, AnimatorStateMachine or AnimatorState
/// - Value: The attached behaviour's source script (C# script or DLL, i.e. MonoScript)
/// - Behaviour: The attached behaviour (MonoBehaviour or StateMachineBehaviour)
/// </summary>
public class BehaviourUsageMatch : ReadOnlySearchMatch
{
public readonly Object Behaviour;
internal BehaviourUsageMatch( Object source, MonoScript value, Object behaviour ) : base( source, value ) { Behaviour = behaviour; }
}
/// <summary>
/// - Source: GameObject Instance
/// - Value: Prefab of that GameObject
/// </summary>
public class PrefabMatch : ReadOnlySearchMatch
{
internal PrefabMatch( Object source, Object value ) : base( source, value ) { }
}
/// <summary>
/// - Source: Object that references Value
/// - Value: Matched object
/// </summary>
public class OtherSearchMatch : GenericSearchMatch
{
internal OtherSearchMatch( object source, Object value, SetterFunction setter ) : base( source, value, setter ) { }
internal OtherSearchMatch( object source, Object value, Object context, SetterFunction setter ) : base( source, value, context, setter ) { }
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3d15ef8bd8f7c7c4e8d228c99713b7eb
timeCreated: 1641132238
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -10,23 +10,23 @@ namespace AssetUsageDetectorNamespace
// 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 MemberInfo variable;
public readonly bool isSerializable;
private readonly VariableGetVal getter;
public string Name { get { return variable.Name; } }
public bool IsProperty { get { return variable is PropertyInfo; } }
public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
{
name = fieldInfo.Name;
isProperty = false;
this.variable = fieldInfo;
this.isSerializable = isSerializable;
this.getter = getter;
}
public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
{
name = propertyInfo.Name;
isProperty = true;
this.variable = propertyInfo;
this.isSerializable = isSerializable;
this.getter = getter;
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "com.yasirkula.assetusagedetector",
"displayName": "Asset Usage Detector",
"version": "2.1.0",
"version": "2.2.0",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",