Skip to content

Tutorial : Random selections

CaptainBubbles edited this page Dec 22, 2014 · 4 revisions

Tutorial 02 : Random selections

Sometimes you may want to choose a random element from a set of objects, which usually looks like this :

GameObject[] possibleEnemies = new GameObject[] {Skeleton, Orc, Demon, Dragon};
GameObject nextEnemy = possibleEnemies[Random.Next(possibleEnemies.Length)];

Easy enough, but what if you want it to be less likely to encounter a dragon? You may end up with a solution like this :

float f = Random.NextFloat();
if(f < 0.5F)
  nextEnemy = Skeleton;
else if (f < 0.8)
...
else
  nextEnemy = Dragon;

This method works, but it is kind of a pain and makes a simple selection much harder than it should be.
RUL provides an easier way to do this:

nextEnemy = Rul.RandElement(possibleEnemies,0.5F,0.3F,0.15F,0.05F);

If you don't specify a probability for each element, RUL will fill in the gaps.

nextEnemy = Rul.RandElement(possibleEnemies,0.9F);

This will generate a skeleton in 9 out of 10 cases with all other enemies being equally rare.
If you want you can also use the RandObject wrapper :

RandObject[] possibleEnemies = new RandObject[] {new RandObject(Skeleton,0.5F), 
new RandObject(Orc,0.3F), new RandObject(Demon,0.15F), new RandObject(Dragon,0.5F)};
GameObject nextEnemy = Rul.RandElement(possibleEnemies);

Another function that may come in handy (especially for card games) is Shuffle .

int[] numbers = new int[] {1,2,3,4,5};
Rul.Shuffle(numbers);
foreach(int i in numbers)
  Console.WriteLine(i);
//=> "4,1,5,3,2"
Clone this wiki locally