需求场景
Unity和C#中都提供的随机数的方法,但实际工作中我们常常需要对不同类型的情况有不同随机概率,这时候就需对随机数做权重处理。
应用代码
为此我抽离了一个随机数权重的静态类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 权重随机数
/// </summary>
public static class WeightRandom
{
/// <summary>
/// 数的区间
/// </summary>
private struct Section
{
public float minValue;
public float maxValue;
}
/// <summary>
/// 区间字典
/// </summary>
private static Dictionary<int, Section> valueSectionDic = new Dictionary<int, Section>();
/// <summary>
/// 初始化随机权重
/// </summary>
public static void Init(float[] weightArray)
{
float startValue = 0;
valueSectionDic.Clear();
for (int i = 0; i < weightArray.Length; i++)
{
Section section = new Section();
section.minValue = startValue;
section.maxValue = startValue + weightArray[i];
valueSectionDic.Add(i, section);
startValue = section.maxValue;
}
}
/// <summary>
/// 获取随机类型
/// </summary>
/// <param name="randmomValue"></param>
/// <returns></returns>
public static int GetRandomType(float randmomValue)
{
for (int i = 0; i < valueSectionDic.Count; i++)
{
if (randmomValue < valueSectionDic[i].maxValue)
{
Debug.Log("weightType: " + i);
return i;
}
}
Debug.Log("weightType: -1");
return -1;
}
/// <summary>
/// 权重水机获取
/// </summary>
/// <param name="weightArray">权重数组(总和为1)</param>
public static int GetWeigtRandom(float[] weightArray)
{
Init(weightArray);
return GetRandomType(Random.Range(0, 1.0f));
}
}
应用代码如下,传入总和为1的随机数权重数组,即可返回对应权重的索引值
public class RandomTest : MonoBehaviour
{
void Update()
{
int type = WeightRandom.GetWeigtRandom(new float[3] {
0.3f, 0.1f, 0.6f });
Debug.Log(type);
}
}