I’m creating an app in Unity that needs to have 6 different players with unique values assigned to them in a random fashion. You click a “roll” button to assign a number from 0 to 5 to each player, but two players can’t have the same number
Example:
After “rolling”; Player 1 is assigned to “4”, Player 2 is assigned to “3”, Player 3 is assigned to “0”, Player 4 is assigned to “5”, Player 5 is assigned to “1”, Player 6 is assigned to “2”.
First add this nice little List extension snippet somewhere:
public static class EnumerableExtension
{
public static void Shuffle<T>( this List<T> list )
{
int count = list.Count;
for(int i = 0; i < count; i++)
list.Swap( i, UnityEngine.Random.Range(i, count) );
}
public static void Swap<T>( this IList<T> list, int i, int j )
{
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
Then, try something like this:
public void AssignInitiative( Player[] players )
{
List<int> list = new List<int>();
for (int i = 0; i < players.Length; i++)
{
list.Add( i );
}
list.Shuffle();
for (int i = 0; i < players.Length; i++)
{
players.initiative = list[i];
}
}