ComponentExtensionMethods.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. var components = new List<T>();
  25. for (var i = 0; i < self.Length; ++i)
  26. {
  27. var range = self[i].GetComponents<T>();
  28. // Skip empty ranges.
  29. if (range == null || range.Length == 0)
  30. {
  31. continue;
  32. }
  33. components.AddRange(range);
  34. }
  35. return components.ToArray();
  36. }
  37. /// <summary>
  38. /// Adds a component to multiple objects.
  39. /// </summary>
  40. /// <typeparam name="T">Component type to add.</typeparam>
  41. /// <param name="self">Array of objects.</param>
  42. /// <returns>Added components.</returns>
  43. public static T[] AddComponentEach<T>(this Component[] self) where T : Component
  44. {
  45. var components = new T[self.Length];
  46. for (var i = 0; i < self.Length; ++i)
  47. {
  48. components[i] = self[i].gameObject.AddComponent<T>();
  49. }
  50. return components;
  51. }
  52. }
  53. }