Pick Random Function By %

So, I have an enemy.

It has 3 functions. Attack 1, Attack 2 and Attack 3.
I want it so there’s a 40% chance for Attack 1, 40*%* chance for Attack 2 and 20% chance for Attack 3.

I’ve been looking into different methods on how to achieve this with enums and switches, but there’s something lacking like the % chance in say, Random.Range.

So, I’m clearly missing something. Got any idea on how to achieve this?

The most straightforward way would be

float val = Random.value

if(val < 0.4f)
  Attack1();
else if (val < 0.8f)
  Attack2();
else
  Attack3();

Theres ways to make this more flexible so you can add more options without having to recalculate the distribution of the value brackets eg.

and then put delegates into an array and index into that

1 Like

Random.Range(0.0f, 1.0f) should give you a value between 0 and 1
Now you can achieve 40% by checking if the value is below 0.4
if not, you can check if it’s below 0.8. Because we already checked if it’s below 0.4, we don’t need to here
and what’s left is the rest of the 100%, 0.8-1

if random < 0.4 then
...
else if random < 0.8 then
...
else
...
endif
1 Like

Well hotdog, that was straight forward. :slight_smile:

Got it working. Perfect!
Thanks for the very quick and thorough answers!