随机指定范围指定数量的随机数
using System.Collections.Generic;
using UnityEngine;
public class RandomNumber : MonoBehaviour
{
public int beginNum, endNum, getCount;
void Awake()
{
beginNum = 1;
endNum = 100;
getCount = 10;
}
/// <summary>
/// 调用
/// </summary>
private void Start()
{
// 从1至100中随机10个不相同的数
List<int> arrayList = GetRandomNumberList(beginNum, endNum, getCount);
for (int i = 0; i < arrayList.Count; i++)
{
Debug.Log("_____________________________________ " + arrayList[i]);
}
}
/// <summary>
/// 随机指定范围指定数量
/// </summary>
/// <param name="beginNum">起始数</param>
/// <param name="endNum">结束数</param>
/// <param name="getCount">随机的数量</param>
/// <returns></returns>
private List<int> GetRandomNumberList(int beginNum, int endNum, int getCount)
{
List<int> resultArray = new List<int>();
List<int> originalArray = new List<int>();
for (int i = beginNum; i <= endNum; i++)
{
originalArray.Add(i);
}
int randomCount = originalArray.Count;
int randomIndex = 0, count = randomCount, temp = 0;
for (int i = 0; i < getCount; i++)
{
randomIndex = UnityEngine.Random.Range(0, count);
resultArray.Add(originalArray[randomIndex]);
if (randomIndex != count - 1)
{
temp = originalArray[randomIndex];
originalArray[randomIndex] = originalArray[count - 1];
originalArray[count - 1] = temp;
}
count--;
}
return resultArray;
}
}