实现一个静态类,里面有打乱数组、列表、字典等方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public static class EnumItemExtends<T>
{
/// <summary>
/// Gets the disrupted items.//返回打乱顺序后的数组
/// </summary>
/// <returns>The disrupted items.</returns>
public static T[] GetDisruptedItems(T[] obj) {
//生成一个新数组:用于在之上计算和返回
T[] item = new T[obj.Length];
for(int i = 0;i < obj.Length;i++) {
item[i] = obj[i];
}
T[] temp;
temp = new T[item.Length];
if(temp.Length <= 2 || item.Length <= 2) {
return item;
}
for(int i = 0;i < temp.Length;i++) { temp[i] = item[i]; }
//打乱数组中元素顺序
System.Random rand = new System.Random();
for(int j = 0;j < temp.Length / 2;j++) {
int x, y; T t;
x = rand.Next(0,temp.Length);
do {
y = rand.Next(0,temp.Length);
} while(y == x);
t = temp[x];
temp[x] = temp[y];
temp[y] = t;
}
return temp;
}
/// <summary>
/// Gets the disrupted items.//返回打乱顺序后的list
/// </summary>
/// <returns>The disrupted items.</returns>
public static List<T> GetDisruptedItems(List<T> obj) {
//生成一个新数组:用于在之上计算和返回
T[] item = new T[obj.Count];
for(int i = 0;i < obj.Count;i++) {
item[i] = obj[i];
}
T[] temp;
temp = new T[item.Length];
if(temp.Length <= 2 || item.Length <= 2) {
return obj;
}
for(int i = 0;i < temp.Length;i++) { temp[i] = item[i]; }
//打乱数组中元素顺序
System.Random rand = new System.Random();
for(int j = 0;j < temp.Length / 2;j++) {
int x, y; T t;
x = rand.Next(0,temp.Length);
do {
y = rand.Next(0,temp.Length);
} while(y == x);
t = temp[x];
temp[x] = temp[y];
temp[y] = t;
}
return new List<T>(temp);
}
/// <summary>
/// Gets the disrupted items.//返回打乱顺序后的dic
/// </summary>
/// <returns>The disrupted items.</returns>
public static Dictionary<T,T> GetDisruptedItems(Dictionary<T,T> obj) {
//生成一个新数组:用于在之上计算和返回
T[] item = new T[obj.Count];
List<T> l_l = new List<T>(obj.Keys);
for(int i = 0;i < l_l.Count;i++) {
item[i] = l_l[i];
}
T[] temp;
temp = new T[item.Length];
if(temp.Length <= 2 || item.Length <= 2) {
return obj;
}
for(int i = 0;i < temp.Length;i++) { temp[i] = item[i]; }
//打乱数组中元素顺序
System.Random rand = new System.Random();
for(int j = 0;j < temp.Length / 2;j++) {
int x, y; T t;
x = rand.Next(0,temp.Length);
do {
y = rand.Next(0,temp.Length);
} while(y == x);
t = temp[x];
temp[x] = temp[y];
temp[y] = t;
}
Dictionary<T,T> dic_return = new Dictionary<T,T>();
for(int q = 0;q < temp.Length;q++) {
dic_return.Add(temp[q],obj[temp[q]]);
}
return dic_return;
}
}
调用方式:
//将targets的顺序打乱 targets是前面定义的数组
GameObject[] trueTargets = EnumItemExtends<GameObject>.GetDisruptedItems(targets);