With this script you can draw an index based on chances. It's really useful!
PropabilityPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DonutStudio.Utilities.Propability
{
/// <summary>
/// Class to draw a random element from a pool of rates.
/// </summary>
public class PropabilityPool
{
float[] rates;
float total;
/// <summary>
/// Create an object of the PropabilityPool class with the rates.
/// </summary>
/// <param name="_rates">The rates of the single elements.</param>
public PropabilityPool(float[] _rates)
{
rates = _rates;
UpdateTotal();
}
/// <summary>
/// Draw a random element for a pool of rates. The higher the rate the higher the chance.
/// </summary>
/// <returns></returns>
public int DrawElement()
{
float r = Random.Range(0f, total);
float accumulatedProbability = 0f;
for (int i = 0; i < rates.Length; i++)
{
accumulatedProbability += rates[i];
if (r <= accumulatedProbability)
return i;
}
return 0;
}
/// <summary>
/// Change the value of a rate.
/// </summary>
/// <param name="index">The index of the rate.</param>
/// <param name="newRate">The new value of the rate.</param>
public void ChangeRate(int index, float newRate)
{
if (index < 0 && index < rates.Length)
return;
rates[index] = newRate;
UpdateTotal();
}
/// <summary>
/// Change all the rates.
/// </summary>
/// <param name="newRates">The rates.</param>
public void ChangeRates(float[] newRates)
{
rates = newRates;
UpdateTotal();
}
/// <summary>
/// Update the total value of all rates
/// </summary>
void UpdateTotal()
{
total = 0;
foreach (float f in rates)
total += f;
}
}
}
8 comments