Guest User

Untitled

a guest
Jun 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class RandomWithWeight : MonoBehaviour {
  6.  
  7. // アイテムのデータを保持する辞書
  8. Dictionary<int, string> itemInfo;
  9.  
  10. // 敵がドロップするアイテムの辞書
  11. Dictionary<int, float> itemDropDict;
  12.  
  13. void Start(){
  14. GetDropItem();
  15. }
  16.  
  17. void GetDropItem(){
  18. // 各種辞書の初期化
  19. InitializeDicts();
  20.  
  21. // ドロップアイテムの抽選
  22. int itemId = Choose();
  23.  
  24. // アイテムIDに応じたメッセージ出力
  25. if (itemId != 0){
  26. string itemName = itemInfo[itemId];
  27. Debug.Log(itemName + " を入手した!");
  28. } else {
  29. Debug.Log("アイテムは入手できませんでした。");
  30. }
  31. }
  32.  
  33. void InitializeDicts(){
  34. itemInfo = new Dictionary<int, string>();
  35. itemInfo.Add(0, "なし");
  36. itemInfo.Add(1, "竜のひげ");
  37. itemInfo.Add(2, "竜の爪");
  38. itemInfo.Add(3, "竜のうろこ");
  39. itemInfo.Add(4, "竜の翼");
  40. itemInfo.Add(5, "竜の逆鱗");
  41. itemInfo.Add(6, "竜の紅玉");
  42.  
  43. itemDropDict = new Dictionary<int, float>();
  44. itemDropDict.Add(0, 60.0f);
  45. itemDropDict.Add(2, 25.0f);
  46. itemDropDict.Add(3, 12.0f);
  47. itemDropDict.Add(5, 3.0f);
  48. }
  49.  
  50. int Choose(){
  51. // 確率の合計値を格納
  52. float total = 0;
  53.  
  54. // 敵ドロップ用の辞書からドロップ率を合計する
  55. foreach (KeyValuePair<int, float> elem in itemDropDict){
  56. total += elem.Value;
  57. }
  58.  
  59. // Random.valueでは0から1までのfloat値を返すので
  60. // そこにドロップ率の合計を掛ける
  61. float randomPoint = Random.value * total;
  62.  
  63. // randomPointの位置に該当するキーを返す
  64. foreach (KeyValuePair<int, float> elem in itemDropDict){
  65. if (randomPoint < elem.Value){
  66. return elem.Key;
  67. } else {
  68. randomPoint -= elem.Value;
  69. }
  70. }
  71. return 0;
  72. }
  73. }
Add Comment
Please, Sign In to add comment