Getting a Random Value from a List of Weighted Values | Unity Game Engine


WeightedValue.cs
1
2
3
4
5
6
7
8
using System;
 
[Serializable]
public class WeightedValue
{
    public string value;
    public int weight;
}

PrintRandomValue.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PrintRandomValue : MonoBehaviour
{
    public List<WeightedValue> weightedValues;
 
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            string randomValue = GetRandomValue(weightedValues);
            Debug.Log(randomValue ?? "No entries found");
        }
    }
 
    string GetRandomValue(List<WeightedValue> weightedValueList)
    {
        string output = null;
 
        //Getting a random weight value
        var totalWeight = 0;
        foreach (var entry in weightedValueList)
        {
            totalWeight += entry.weight;
        }
        var rndWeightValue = Random.Range(1, totalWeight + 1);
 
        //Checking where random weight value falls
        var processedWeight = 0;
        foreach (var entry in weightedValueList)
        {
            processedWeight += entry.weight;
            if(rndWeightValue <= processedWeight)
            {
                output = entry.value;
                break;
            }
        }
 
        return output;
    }
}