SpriteExtensions.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.U2D;
  4. #if UNITY_EDITOR
  5. using System.Reflection;
  6. #endif
  7. namespace Coffee.UIParticleInternal
  8. {
  9. /// <summary>
  10. /// Extension methods for Sprite class.
  11. /// </summary>
  12. internal static class SpriteExtensions
  13. {
  14. #if UNITY_EDITOR
  15. private static readonly Type s_SpriteEditorExtensionType =
  16. Type.GetType("UnityEditor.Experimental.U2D.SpriteEditorExtension, UnityEditor")
  17. ?? Type.GetType("UnityEditor.U2D.SpriteEditorExtension, UnityEditor");
  18. private static readonly Func<Sprite, Texture2D> s_GetActiveAtlasTextureMethod =
  19. (Func<Sprite, Texture2D>)Delegate.CreateDelegate(typeof(Func<Sprite, Texture2D>),
  20. s_SpriteEditorExtensionType
  21. .GetMethod("GetActiveAtlasTexture", BindingFlags.Static | BindingFlags.NonPublic));
  22. private static readonly Func<Sprite, SpriteAtlas> s_GetActiveAtlasMethod =
  23. (Func<Sprite, SpriteAtlas>)Delegate.CreateDelegate(typeof(Func<Sprite, SpriteAtlas>),
  24. s_SpriteEditorExtensionType
  25. .GetMethod("GetActiveAtlas", BindingFlags.Static | BindingFlags.NonPublic));
  26. /// <summary>
  27. /// Get the actual texture of a sprite in play mode or edit mode.
  28. /// </summary>
  29. public static Texture2D GetActualTexture(this Sprite self)
  30. {
  31. if (!self) return null;
  32. var ret = s_GetActiveAtlasTextureMethod(self);
  33. return ret ? ret : self.texture;
  34. }
  35. /// <summary>
  36. /// Get the active sprite atlas of a sprite in play mode or edit mode.
  37. /// </summary>
  38. public static SpriteAtlas GetActiveAtlas(this Sprite self)
  39. {
  40. if (!self) return null;
  41. return s_GetActiveAtlasMethod(self);
  42. }
  43. #else
  44. /// <summary>
  45. /// Get the actual texture of a sprite in play mode.
  46. /// </summary>
  47. internal static Texture2D GetActualTexture(this Sprite self)
  48. {
  49. return self ? self.texture : null;
  50. }
  51. #endif
  52. }
  53. }