NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/Utils/ArrayEx.cs

65 lines
1.7 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace Gameplay
{
public static class ArrayEx
{
public static List<T> RandomArrayFromArray<T>(List<T> list,
int count)
{
if (list.Count < count)
{
throw new System.Exception("传入list长度不足");
}
var cloneList = new List<T>(list);
var result = new List<T>();
for (var i = 0; i < count; ++i)
{
var index = Random.Range(0, cloneList.Count);
result.Add(cloneList[index]);
cloneList.RemoveAt(index);
}
return result;
}
public static T RandomFromArray<T>(List<T> list)
{
var randomIndex = Random.Range(0, list.Count);
return list[randomIndex];
}
public static T RandomFromArray<T>(T[] list)
{
var randomIndex = Random.Range(0, list.Length);
return list[randomIndex];
}
public static T RandomWithWeights<T>(List<T> list,
List<int> weights)
{
var totalWeight = 0;
for (var i = 0; i < weights.Count; ++i)
{
totalWeight += weights[i];
}
var randomValue = Random.Range(0, totalWeight);
var currentWeight = 0;
for (var i = 0; i < weights.Count; ++i)
{
currentWeight += weights[i];
if (randomValue < currentWeight)
{
return list[i];
}
}
return list[^1];
}
}
}