ComponentExtensionMethods.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright(c) Live2D Inc. All rights reserved.
  3. *
  4. * Use of this source code is governed by the Live2D Open Software license
  5. * that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
  6. */
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. namespace Live2D.Cubism.Framework
  10. {
  11. /// <summary>
  12. /// Extensions for <see cref="Component"/>s.
  13. /// </summary>
  14. public static class ComponentExtensionMethods
  15. {
  16. /// <summary>
  17. /// Gets components for each item of a sequence and flattens the resulting sequences into one sequence.
  18. /// </summary>
  19. /// <typeparam name="T">Component type to find.</typeparam>
  20. /// <param name="self">Array to query.</param>
  21. /// <returns>Matches.</returns>
  22. public static T[] GetComponentsMany<T>(this Component[] self) where T : Component
  23. {
  24. if (self == null)
  25. {
  26. return null;
  27. }
  28. var components = new List<T>();
  29. for (var i = 0; i < self.Length; ++i)
  30. {
  31. var range = self[i].GetComponents<T>();
  32. // Skip empty ranges.
  33. if (range == null || range.Length == 0)
  34. {
  35. continue;
  36. }
  37. components.AddRange(range);
  38. }
  39. return components.ToArray();
  40. }
  41. /// <summary>
  42. /// Adds a component to multiple objects.
  43. /// </summary>
  44. /// <typeparam name="T">Component type to add.</typeparam>
  45. /// <param name="self">Array of objects.</param>
  46. /// <returns>Added components.</returns>
  47. public static T[] AddComponentEach<T>(this Component[] self) where T : Component
  48. {
  49. if (self == null)
  50. {
  51. return null;
  52. }
  53. var components = new T[self.Length];
  54. for (var i = 0; i < self.Length; ++i)
  55. {
  56. components[i] = self[i].gameObject.AddComponent<T>();
  57. }
  58. return components;
  59. }
  60. }
  61. }