Unity不重复随机
时间: 2024-04-25 11:25:07 浏览: 171
Procedural.Content.Generation.for.Unity.Game.Development.Jan.2016
Unity中实现不重复随机的方法有多种。一种方法是使用HashSet来存储随机数,直到HashSet的大小达到所需的数量为止。可以借用System.Random类生成随机数,并使用HashSet的Add方法来确保不重复。以下是一个示例代码:
```csharp
HashSet<int> nums = new HashSet<int>();
System.Random r = new System.Random();
while (nums.Count != 5) {
nums.Add(r.Next(0, 5));
}
foreach (var item in nums) {
Debug.Log(item);
}
```
另一种方法是使用一个总数组和一个输出数组,通过交换元素的方式来实现不重复随机。首先,将总数组填充为连续的数字序列。然后,从总数组中随机选择一个数,并将其与总数组的最后一个数交换位置。每次选择一个数后,将总数组的范围缩小一个,以确保不会重复选择。以下是一个示例代码:
```csharp
public int\[\] GetRandomSequence(int total, int n) {
int\[\] sequence = new int\[total\];
int\[\] output = new int\[n\];
for (int i = 0; i < total; i++) {
sequence\[i\] = i;
}
int end = total - 1;
for (int i = 0; i < n; i++) {
int num = UnityEngine.Random.Range(0, end + 1);
output\[i\] = sequence\[num\];
sequence\[num\] = sequence\[end\];
end--;
}
return output;
}
```
还可以使用MathMode类中的GetNoRepeatRandomInList方法来从一个列表中取出不重复的随机数。该方法使用UnityEngine.Random.Range生成随机索引,并从列表中移除已选择的元素。以下是一个示例代码:
```csharp
public static T GetNoRepeatRandomInList<T>(ref List<T> list) {
int index = UnityEngine.Random.Range(0, list.Count);
T result = list\[index\];
list.RemoveAt(index);
return result;
}
```
以上是Unity中实现不重复随机的几种方法。您可以根据具体需求选择适合的方法来生成不重复的随机数。
#### 引用[.reference_title]
- *1* [Unity实现不重复随机数](https://blog.csdn.net/alone_ws/article/details/86588846)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Unity C# 基础复习19——HashSet(P384)获取不重复随机数](https://blog.csdn.net/weixin_46711336/article/details/124512755)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Unity 生成不重复随机数](https://blog.csdn.net/qq_36848370/article/details/105816424)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文