using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; [CreateAssetMenu(fileName = "GrantPool", menuName = "ScriptableObject/NodeGrantPool", order = 1)] public class NodeGrantPool : ScriptableObject { public List AllItems; public Sprite DesImage; public PHomePush.NodeChoseItem GetOneItemRandom() { return GetOneItemRandomFromList(AllItems); } public IEnumerable GetItemsRandom(int count = 1, bool allowRepeat = false) { if (count <= 0) { yield break; } if (allowRepeat) { for (int i = 0; i < count; i++) { yield return GetOneItemRandom(); } } else { if (AllItems.Count < count) { throw new System.Exception($"Item pool only contains {AllItems.Count} items, but trying to get {count}"); } if (count == 1) { yield return GetOneItemRandom(); yield break; } else if (count == AllItems.Count) { foreach (var item in AllItems) { yield return item; } yield break; } List availableItems = new List(AllItems); for (int i = 0; i < count; i++) { var item = GetOneItemRandomFromList(availableItems); availableItems.Remove(item); yield return item; } } } public static PHomePush.NodeChoseItem GetOneItemRandomFromList(List list) { // 计算总权重 float totalWeight = list.Sum(x => x.Weight); // 根据总权重随机选择一个值 float randomPoint = Random.Range(0, totalWeight); // 根据随机值选择项目 float currentPoint = 0f; foreach (var item in list) { currentPoint += item.Weight; if (randomPoint <= currentPoint) { return item; } } throw new System.Exception($"Nothing to chose from"); } }