ItemSelection.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace HQFPSWeapons
  4. {
  5. public static class ItemSelection
  6. {
  7. public static T Select<T>(this T[] array, ref int last, Method selectionMethod = Method.Random)
  8. {
  9. if(array == null || array.Length == 0)
  10. return default(T);
  11. int next = 0;
  12. if(selectionMethod == Method.Random)
  13. next = Random.Range(0, array.Length);
  14. else if(selectionMethod == Method.RandomExcludeLast && array.Length > 1)
  15. {
  16. last = Mathf.Clamp(last, 0, array.Length - 1);
  17. T first = array[0];
  18. array[0] = array[last];
  19. array[last] = first;
  20. next = Random.Range(1, array.Length);
  21. }
  22. else if(selectionMethod == Method.Sequence)
  23. next = (int)Mathf.Repeat(last + 1, array.Length);
  24. last = next;
  25. return array[next];
  26. }
  27. public static T Select<T>(this List<T> list, ref int last, Method selectionMethod = Method.Random)
  28. {
  29. if(list == null || list.Count == 0)
  30. return default(T);
  31. int next = 0;
  32. if(selectionMethod == Method.Random)
  33. next = Random.Range(0, list.Count);
  34. else if(selectionMethod == Method.RandomExcludeLast && list.Count > 1)
  35. {
  36. last = Mathf.Clamp(last, 0, list.Count - 1);
  37. T first = list[0];
  38. list[0] = list[last];
  39. list[last] = first;
  40. next = Random.Range(1, list.Count);
  41. }
  42. else if(selectionMethod == Method.Sequence)
  43. next = (int)Mathf.Repeat(last + 1, list.Count);
  44. last = next;
  45. return list[next];
  46. }
  47. // ------------------------ Internal Declarations ------------------------
  48. public enum Method
  49. {
  50. /// <summary>The item will be selected randomly.</summary>
  51. Random,
  52. /// <summary>The item will be selected randomly, but will exclude the last selected.</summary>
  53. RandomExcludeLast,
  54. /// <summary>The items will be selected in sequence.</summary>
  55. Sequence
  56. }
  57. }
  58. }