1. 程式人生 > 其它 >Unity中根據權重隨機獲取值

Unity中根據權重隨機獲取值

技術標籤:Unity開發實戰

一:實現思路


計算不同id對應的權重總和並加入到權重區間字典中,例如id1的區間為0-10,id2的區間為10-30,id3的區間為30-60.....隨機獲取值的時候將隨機值和權重區間字典中的每一個值依次做比較


二:完整程式碼

using UnityEngine;
using System.Collections.Generic;
using System.Linq;

public class Test : MonoBehaviour
{
    private Dictionary<string, int> weightDict = new Dictionary<string, int>();//權重字典

    private Dictionary<string, int> weightSectionDict = new Dictionary<string, int>();//權重區間字典

    private void Awake()
    {
        weightDict.Add("Id1", 10);
        weightDict.Add("Id2", 20);
        weightDict.Add("Id3", 30);
        weightDict.Add("Id4", 50);
        weightDict.Add("Id5", 40);

        //計算權重區間
        CalcWeightSection();
    }

    /// <summary>
    /// 得到總權重
    /// </summary>
    private int GetTotalWeight()
    {
        int totalWeight = 0;
        foreach (var weight in weightDict.Values)
        {
            totalWeight += weight;
        }
        return totalWeight;
    }

    /// <summary>
    /// 計算權重區間
    /// </summary>
    private void CalcWeightSection()
    {
        int count = weightDict.Count;
        for (int i = 1; i <= count; i++)
        {
            string id = weightDict.ElementAt(i - 1).Key;
            int tempWeight = 0;
            for (int j = 0; j < i; j++)
            {
                tempWeight += weightDict.ElementAt(j).Value;
            }
            weightSectionDict.Add(id, tempWeight);
        }
    }

    /// <summary>
    /// 得到隨機的id
    /// </summary>
    private string GetRanId()
    {
        int ranNum = Random.Range(0, GetTotalWeight() + 1);
        for (int i = 0; i < weightSectionDict.Count; i++)
        {
            int temp = weightSectionDict.ElementAt(i).Value;
            if (ranNum <= temp)
            {
                Debug.Log(string.Format("隨機數字:{0},隨機結果:{1}", ranNum, weightDict.ElementAt(i).Key));
                return weightDict.ElementAt(i).Key;
            }
        }
        return "";
    }

    /// <summary>
    /// 測試用
    /// </summary>
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            string ranId = GetRanId();
        }
    }
}