WeightRandomUtils.cs 906 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace WildAttack
  5. {
  6. /// <summary>
  7. /// 根据权重随机
  8. /// </summary>
  9. public class WeightRandomUtils : Singleton<WeightRandomUtils>
  10. {
  11. public int GetRandomId(List<int> weightList)
  12. {
  13. int rdm = Random.Range(0, GetTotalWeight(weightList) + 1);
  14. int limit = 0;
  15. for (int i = 0; i < weightList.Count; i++)
  16. {
  17. limit += weightList[i];
  18. if (rdm <= limit)
  19. {
  20. return i + 1;
  21. }
  22. }
  23. return -1;
  24. }
  25. private int GetTotalWeight(List<int> weightList)
  26. {
  27. int total = 0;
  28. foreach (var item in weightList)
  29. {
  30. total += item;
  31. }
  32. return total;
  33. }
  34. }
  35. }