Compare commits

...

9 Commits

Author SHA1 Message Date
yasirkula cb4454b493 - Terrains are now searched properly
- Fixed an error on latest Unity versions when clicking the "Reset Search" button
2022-07-23 21:53:11 +03:00
yasirkula dfb8541605 Fixed compiler errors on 2021.2 and later 2022-04-24 15:14:47 +03:00
yasirkula 4b146280ab (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 2022-01-05 10:18:17 +03:00
yasirkula 8a6fe822d6 Materials instantiated (cloned) at runtime are now searched correctly 2022-01-05 10:17:07 +03:00
yasirkula c9ceab6085 Fixed Settings not fitting inside Preferences window on older Unity versions 2022-01-04 23:24:55 +03:00
yasirkula 4fddcb7b80 Simplified "Can't search unloaded scenes in play mode" warnings 2022-01-04 23:24:49 +03:00
yasirkula 001df6eb6c Fixed locked AssetUsageDetector windows entering an inconsistent state after relaunching the editor 2022-01-04 23:24:30 +03:00
yasirkula 60f8d30810 Undo'ed a previous change that resulted in some particle system variables not being searched in play mode 2022-01-04 23:20:38 +03:00
yasirkula c9dbd2d201 Fixed README.txt link in documentation 2022-01-01 21:47:43 +03:00
11 changed files with 837 additions and 53 deletions
+28 -1
View File
@@ -30,13 +30,40 @@ There are 5 ways to install this plugin:
- Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!**
- or, right click an object and select **Search For References**
- To learn how to interpret the search results and for more instructions, please see the included [README.txt](Plugins/AssetUsageDetector/README.txt) file
- To learn how to interpret the search results and for more instructions, please see the included [README.txt](../Plugins/AssetUsageDetector/README.txt) file
- You can tweak most settings/colors via *Project Settings/yasirkula/Asset Usage Detector* page (on older versions, this menu is located at *Preferences* window)
![SearchResults1](Images/SearchResults1Dark.png)
![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
@@ -10,7 +10,7 @@ using System;
using System.IO;
using System.Text;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -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();
@@ -321,16 +318,28 @@ namespace AssetUsageDetectorNamespace
openScenes.Add( scene.path );
}
List<string> skippedScenes = new List<string>( scenesToSearch.Count );
scenesToSearch.RemoveWhere( ( path ) =>
{
if( !openScenes.Contains( path ) )
{
Debug.Log( "Can't search unloaded scenes while in play mode, skipped " + path );
skippedScenes.Add( path );
return true;
}
return false;
} );
if( skippedScenes.Count > 0 )
{
StringBuilder sb = Utilities.stringBuilder;
sb.Length = 0;
sb.Append( "Can't search unloaded scenes while in play mode, skipped " ).Append( skippedScenes.Count ).AppendLine( " scene(s):" );
for( int i = 0; i < skippedScenes.Count; i++ )
sb.Append( "- " ).AppendLine( skippedScenes[i] );
Debug.Log( sb.ToString() );
}
}
// Initialize data used by search functions
@@ -533,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;
@@ -821,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 );
}
@@ -1050,7 +1059,7 @@ namespace AssetUsageDetectorNamespace
else
{
// Comply with the recursive search limit
if( currentDepth >= searchDepthLimit )
if( currentDepth >= searchParameters.searchDepthLimit )
return null;
callStack.Add( obj );
@@ -216,6 +216,7 @@ namespace AssetUsageDetectorNamespace
{ typeof( AnimatorStateTransition ), SearchAnimatorStateTransition },
{ typeof( BlendTree ), SearchBlendTree },
{ typeof( AnimationClip ), SearchAnimationClip },
{ typeof( TerrainData ), SearchTerrainData },
#if UNITY_2017_1_OR_NEWER
{ typeof( SpriteAtlas ), SearchSpriteAtlas },
#endif
@@ -358,13 +359,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 +398,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 +442,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 +461,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,10 +478,118 @@ 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
else if( component is ParticleSystemRenderer )
{
// Search ParticleSystemRenderer's custom meshes for references (at runtime, they can't be searched with reflection, unfortunately)
if( isInPlayMode && !AssetDatabase.Contains( component ) )
{
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 )
{
// At runtime, some ParticleSystem properties can't be searched with reflection, search them manually here
if( isInPlayMode && !AssetDatabase.Contains( component ) )
{
ParticleSystem particleSystem = (ParticleSystem) component;
try
{
ParticleSystem.CollisionModule collisionModule = particleSystem.collision;
#if UNITY_2020_2_OR_NEWER
for( int i = 0, j = collisionModule.planeCount; i < j; i++ )
#else
for( int i = 0, j = collisionModule.maxPlaneCount; i < j; i++ )
#endif
{
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 { }
try
{
ParticleSystem.TriggerModule triggerModule = particleSystem.trigger;
#if UNITY_2020_2_OR_NEWER
for( int i = 0, j = triggerModule.colliderCount; i < j; i++ )
#else
for( int i = 0, j = triggerModule.maxColliderCount; i < j; i++ )
#endif
{
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 { }
#if UNITY_2017_1_OR_NEWER
try
{
ParticleSystem.TextureSheetAnimationModule textureSheetAnimationModule = particleSystem.textureSheetAnimation;
for( int i = 0, j = textureSheetAnimationModule.spriteCount; i < j; i++ )
{
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 { }
#endif
#if UNITY_5_5_OR_NEWER
try
{
ParticleSystem.SubEmittersModule subEmittersModule = particleSystem.subEmitters;
for( int i = 0, j = subEmittersModule.subEmittersCount; i < j; i++ )
{
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 { }
#endif
}
}
SearchVariablesWithSerializedObject( referenceNode );
return referenceNode;
@@ -479,7 +631,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 + "]" );
@@ -496,6 +648,28 @@ namespace AssetUsageDetectorNamespace
referenceNode.RemoveLink( i );
}
// At runtime, Textures assigned to clone materials can't be searched with reflection, search them manually here
if( searchTextureReferences && isInPlayMode && !AssetDatabase.Contains( material ) )
{
Shader shader = material.shader;
int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader );
for( int i = 0; i < shaderPropertyCount; i++ )
{
if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv )
{
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 ) ) );
}
}
}
}
return referenceNode;
}
@@ -523,7 +697,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 ) );
}
}
}
}
@@ -570,11 +749,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 ) );
}
}
}
}
@@ -593,8 +777,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 ) );
}
}
@@ -604,7 +793,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;
@@ -635,7 +850,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] ) );
}
}
}
@@ -649,6 +869,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;
@@ -656,7 +879,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] ) );
}
}
}
@@ -676,8 +904,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;
}
@@ -692,15 +925,53 @@ 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;
}
// TerrainData's properties like tree/detail/layer definitions aren't exposed to SerializedObject so use reflection instead
private ReferenceNode SearchTerrainData( Object unityObject )
{
ReferenceNode referenceNode = PopReferenceNode( unityObject );
SearchVariablesWithReflection( referenceNode );
return referenceNode;
}
@@ -713,24 +984,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
@@ -1096,28 +1382,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;
@@ -1129,7 +1421,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 ) );
@@ -1164,7 +1461,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 ) )
@@ -1172,14 +1474,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 ) { }
@@ -1193,7 +1512,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 );
@@ -1316,6 +1635,11 @@ namespace AssetUsageDetectorNamespace
// Ignore "meshFilter" property of TextMeshPro and TMP_SubMesh components because this property adds a MeshFilter component to the object if it doesn't exist
else if( propertyName == "meshFilter" && ( currType.Name == "TextMeshPro" || currType.Name == "TMP_SubMesh" ) )
continue;
// Ignore "users" property of TerrainData because it returns the Terrains in the scene that use that TerrainData. This causes issues with callStack because TerrainData
// is already in callStack when Terrains are searched via "users" property of it and hence, Terrain->TerrainData references for that TerrainData can't be found in scenes
// (this is how callStack works, it prevents searching an object if it's already in callStack to avoid infinite recursion)
else if( propertyName == "users" && typeof( TerrainData ).IsAssignableFrom( currType ) )
continue;
else
{
VariableGetVal getter = property.CreateGetter();
@@ -1338,7 +1662,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( '.' );
@@ -171,7 +171,11 @@ namespace AssetUsageDetectorNamespace
public static void PreferencesGUI()
{
float labelWidth = EditorGUIUtility.labelWidth;
#if UNITY_2018_3_OR_NEWER
EditorGUIUtility.labelWidth += 60f;
#else
EditorGUIUtility.labelWidth += 20f;
#endif
EditorGUI.BeginChangeCheck();
@@ -5,7 +5,10 @@ using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -46,6 +49,8 @@ namespace AssetUsageDetectorNamespace
// This isn't readonly so that it can be serialized
private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };
#pragma warning disable 0649
[SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked
private bool m_isLocked;
private bool IsLocked
{
@@ -59,6 +64,7 @@ namespace AssetUsageDetectorNamespace
}
}
}
#pragma warning restore 0649
private Phase currentPhase = Phase.Setup;
@@ -87,6 +93,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 );
@@ -166,6 +174,8 @@ namespace AssetUsageDetectorNamespace
if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
{
window.Show();
window.Focus();
return window;
}
@@ -188,6 +198,8 @@ namespace AssetUsageDetectorNamespace
}
window.Show( true );
window.Focus();
return window;
}
@@ -297,6 +309,7 @@ namespace AssetUsageDetectorNamespace
propertyModifiers = searchParameters.propertyModifiers;
searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
searchRefactoring = searchParameters.searchRefactoring;
lazySceneSearch = searchParameters.lazySceneSearch;
calculateUnusedObjects = searchParameters.calculateUnusedObjects;
hideDuplicateRows = searchParameters.hideDuplicateRows;
@@ -448,7 +461,10 @@ namespace AssetUsageDetectorNamespace
GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );
if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
}
else if( currentPhase == Phase.Setup )
{
@@ -563,7 +579,10 @@ namespace AssetUsageDetectorNamespace
GUI.enabled = true;
if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
{
ReturnToSetupPhase();
GUIUtility.ExitGUI();
}
if( searchResult == null )
{
@@ -659,6 +678,7 @@ namespace AssetUsageDetectorNamespace
//searchDepthLimit = searchDepthLimit,
//searchNonSerializableVariables = searchNonSerializableVariables,
searchUnusedMaterialProperties = searchUnusedMaterialProperties,
searchRefactoring = searchRefactoring,
lazySceneSearch = lazySceneSearch,
calculateUnusedObjects = calculateUnusedObjects,
hideDuplicateRows = hideDuplicateRows,
@@ -669,6 +689,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:
@@ -5,7 +5,10 @@ using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -10,7 +10,7 @@ using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
#if UNITY_2018_3_OR_NEWER
#if UNITY_2018_3_OR_NEWER && !UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif
@@ -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.2",
"documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector",
"changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases",
"licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt",