数组和列表方法拓展,复制到一个静态类里即可使用
public static T[] GetRandomChilds<T>(this T[] array,int count)
{
T[] tempArray = new T[array.Length];
T[] tempResultArray = new T[count];
array.CopyTo(tempArray,0);
tempArray.SortRandom<T>();
System.Array.Copy(tempArray,tempResultArray,count);
return tempResultArray;
}
public static List<T> GetRandomChilds<T>(this List<T> list,int count)
{
List<T> tempList = new List<T>();
tempList.AddRange(list);
tempList.SortRandom<T>();
return tempList.GetRange(0,count);
}
public static void Swap<T>(this T[] array, int index1, int index2)
{
T temp = array[index2];
array[index2] = array[index1];
array[index1] = temp;
}
public static void Swap<T>(this List<T> list, int index1, int index2)
{
T temp = list[index2];
list[index2] = list[index1];
list[index1] = temp;
}
public static T[] SortRandom<T>(this T[] array)
{
int randomIndex;
for (int i = array.Length - 1; i > 0; i--)
{
randomIndex = UnityEngine.Random.Range(0, i);
array.Swap(randomIndex, i);
}
return array;
}
public static List<T> SortRandom<T>(this List<T> list)
{
int randomIndex;
for (int i = list.Count - 1; i > 0; i--)
{
randomIndex = UnityEngine.Random.Range(0, i);
list.Swap(randomIndex, i);
}
return list;
}
调用如下
int count = 5;
int[] array= new int[] { 0, 1, 2, 3, 4, 5, 6, 7 };
int[] arrayTemp = array.GetRandomChilds<int>(count);
List<string> list = new List<string>(){"a", "b", "c", "d", "e", "f", "g"};
List<string> listTemp = list.GetRandomChilds<string>(count);