You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.9 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. /// <summary>
  7. /// Class used to write extension methodes in
  8. /// </summary>
  9. public static class ExtensionMethods
  10. {
  11. /// <summary>
  12. /// Converts provided Direction to Global Vector3
  13. /// </summary>
  14. /// <param name="direction">Direction to convert</param>
  15. /// <returns>Global Vector3 direction</returns>
  16. public static Vector3 ToVector(this Direction direction)
  17. {
  18. switch (direction)
  19. {
  20. case Direction.Forward:
  21. return Vector3.forward;
  22. case Direction.Right:
  23. return Vector3.right;
  24. case Direction.Back:
  25. return Vector3.back;
  26. case Direction.Left:
  27. return Vector3.left;
  28. default:
  29. return Vector3.zero;
  30. }
  31. }
  32. /// <summary>
  33. /// Converts provided Direction to local Vector3
  34. /// </summary>
  35. /// <param name="direction">Direction to convert</param>
  36. /// <param name="transform">Transform to use as directions local space</param>
  37. /// <returns>Local Vector3 direction</returns>
  38. public static Vector3 ToVector(this Direction direction, Transform transform)
  39. {
  40. switch (direction)
  41. {
  42. case Direction.Forward:
  43. return transform.forward;
  44. case Direction.Right:
  45. return transform.right;
  46. case Direction.Back:
  47. return -transform.forward;
  48. case Direction.Left:
  49. return -transform.right;
  50. default:
  51. return Vector3.zero;
  52. }
  53. }
  54. /// <summary>
  55. /// Gets the rect of a RectTransform in World coordinates
  56. /// </summary>
  57. /// <param name="rt">RectTransform to get rect from</param>
  58. /// <returns>rect of a RectTransform in World coordinates </returns>
  59. public static Rect GlobalRect(this RectTransform rt)
  60. {
  61. var r = rt.rect;
  62. Vector2 centre = rt.TransformPoint(r.center);
  63. r.size = rt.TransformVector(r.size);
  64. r.center = centre;
  65. return r;
  66. }
  67. /// <summary>
  68. /// Applies an action to each element in an IEnumerable
  69. /// </summary>
  70. /// <param name="enumeration">IEnumerable to loop therough</param>
  71. /// <param name="action">Action to apply to each element</param>
  72. public static void ForEach<T>(this IEnumerable<T> enumeration, System.Action<T> action)
  73. {
  74. foreach (T item in enumeration)
  75. action(item);
  76. }
  77. public static T maxBy<T>(this IEnumerable<T> values, Func<T, IComparable> predicate)
  78. {
  79. //Define smallest value as first
  80. T max = values.First();
  81. //compare all other values
  82. foreach (T item in values)
  83. if (predicate(item).CompareTo(predicate(max)) > 0)
  84. max = item;
  85. return max;
  86. }
  87. }