IWrapper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using System;
  3. using UnityEngine;
  4. namespace Animancer
  5. {
  6. /// <summary>An object which wraps a <see cref="WrappedObject"/> object.</summary>
  7. /// https://kybernetik.com.au/animancer/api/Animancer/IWrapper
  8. public interface IWrapper
  9. {
  10. /************************************************************************************************************************/
  11. /// <summary>The wrapped object.</summary>
  12. /// <remarks>
  13. /// Use <see cref="AnimancerUtilities.TryGetWrappedObject"/>
  14. /// in case the <see cref="WrappedObject"/> is also an <see cref="IWrapper"/>.
  15. /// </remarks>
  16. object WrappedObject { get; }
  17. /************************************************************************************************************************/
  18. }
  19. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerUtilities
  20. public partial class AnimancerUtilities
  21. {
  22. /************************************************************************************************************************/
  23. /// <summary>
  24. /// Returns the last <see cref="IWrapper.WrappedObject"/>
  25. /// which is a <typeparamref name="T"/>, including the `wrapper` itself.
  26. /// </summary>
  27. public static bool TryGetWrappedObject<T>(
  28. object wrapper,
  29. out T wrapped,
  30. bool logException = false)
  31. where T : class
  32. {
  33. wrapped = default;
  34. while (true)
  35. {
  36. if (wrapper is T t)
  37. wrapped = t;
  38. if (wrapper is IWrapper targetWrapper)
  39. {
  40. try
  41. {
  42. wrapper = targetWrapper.WrappedObject;
  43. }
  44. catch (Exception exception)
  45. {
  46. if (logException)
  47. Debug.LogException(exception);
  48. break;
  49. }
  50. }
  51. else
  52. {
  53. break;
  54. }
  55. }
  56. return wrapped != null;
  57. }
  58. /************************************************************************************************************************/
  59. }
  60. }