Recently we stumbled across the need to get all sprites that can appear in a 2D Animator. This topic however is not covered very well in the Unity docs, so we now that we figured out how to get it done, we thought hey why not share it ?
Well take a look at this snippet if you are interested in this :
public static List<Sprite> GetSpritesFromAnimator(Animator anim) { List<Sprite> _allSprites = new List<Sprite> (); foreach(AnimationClip ac in anim.runtimeAnimatorController.animationClips) { _allSprites.AddRange(GetSpritesFromClip(ac)); } return _allSprites; } private static List<Sprite> GetSpritesFromClip(AnimationClip clip) { var _sprites = new List<Sprite> (); if (clip != null) { foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings (clip)) { ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve (clip, binding); foreach (var frame in keyframes) { _sprites.Add ((Sprite)frame.value); } } } return _sprites; }
Now all you need to do is call
GetSpritesFromAnimator(_anim)
and pass your animator component to the function, and you will get a list of all sprites back that are used by any animation inside this animator!
( We only used it inside the Editor, not sure if it does work at runtime ) As always, don't hesitate to contact us if you got any questions or suggestions. Happy coding!