1 using UnityEngine; 2 using System.Collections; 3 using System.Collections.Generic; 4 5 public class BaseLootTable 6 { 7 private List<LootTableEntry> lootEntries = new List<LootTableEntry>(); 8 //The sum of all of the entries' weights 9 private int totalWeights = 0; 10 //Item weights as overall percentages 11 private List<int> weightPercentages = new List<int>(); 12 //The cumulative percentage table to check against 13 private List<int> cumulativePercentages = new List<int>(); 14 15 protected void InitTable() 16 { 17 GetTotalWeights(); 18 GetWeightPercentages(); 19 GetCumulativePercentages(); 20 } 21 22 public List<BaseItem> GetLoot() 23 { 24 int check = Random.Range(1, 101); 25 26 for (int i = 0; i < cumulativePercentages.Count - 1; i++) 27 { 28 //Check if the random number we generated is between this set of values 29 if (check > cumulativePercentages[i] && check <= cumulativePercentages[i + 1]) 30 { 31 return lootEntries[i].Items; 32 } 33 } 34 35 return new List<BaseItem>(); 36 } 37 38 private void GetTotalWeights() 39 { 40 totalWeights = 0; 41 42 //Add all of the items' Weights together 43 foreach (LootTableEntry entry in lootEntries) 44 { 45 totalWeights += entry.Weight; 46 } 47 } 48 49 private void GetWeightPercentages() 50 { 51 weightPercentages.Clear(); 52 53 for (int i = 0; i < lootEntries.Count; i++ ) 54 { 55 //Get the probability of the item based upon the total probability 56 int percent = Mathf.RoundToInt(((float)lootEntries[i].Weight / (float)totalWeights) * 100); 57 58 weightPercentages.Add(percent); 59 } 60 } 61 62 private void GetCumulativePercentages() 63 { 64 cumulativePercentages.Clear(); 65 66 int cumulativePercent = 0; 67 cumulativePercentages.Add(cumulativePercent); 68 for (int i = 0; i < weightPercentages.Count; i++) 69 { 70 //Add the new item's probability 71 cumulativePercent += weightPercentages[i]; 72 73 //add the new percent as the key, and the index of the associated entry as the value 74 cumulativePercentages.Add(cumulativePercent); 75 } 76 } 77 78 protected void AddNewEntry(int probability, params BaseItem[] items) 79 { 80 lootEntries.Add(new LootTableEntry(probability, new List<BaseItem>(items))); 81 } 82 } 83