-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListRandomExtensions.cs
54 lines (45 loc) · 1.33 KB
/
ListRandomExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System.Collections.Generic;
using UnityEngine;
namespace Codeavr.RandomExtensions
{
public static class ListRandomExtensions
{
/// <summary>
/// Remove and return random item
/// </summary>
/// <returns>Random item, or default(T)</returns>
public static T PopRandom<T>(this List<T> list)
{
int index = Random.Range(0, list.Count);
T item = list[index];
list.RemoveAt(index);
return item;
}
/// <summary>
/// Return random item
/// </summary>
/// <returns>Random item, or default(T)</returns>
public static T PickRandom<T>(this List<T> list)
{
if (list == null || list.Count <= 0)
{
return default;
}
int randomIndex = Random.Range(0, list.Count);
return list[randomIndex];
}
/// <summary>
/// Return random item
/// </summary>
/// <returns>Random item, or default(T)</returns>
public static T PickRandom<T>(this IReadOnlyList<T> list)
{
if (list == null || list.Count <= 0)
{
return default;
}
int randomIndex = Random.Range(0, list.Count);
return list[randomIndex];
}
}
}