- Home /
Clean way for percentages
Hi, I am looking for a cleaner solution for a random outcome of an event with using percentages. My academic English is not enough to tell it in better words so I allow editing on the question. To explain it with example; I have 3 events that are 50-30-20 percent chance to happen. My dirty way to handle it:
int tempnum = Random.Range(0, 10);
if (tempnum < 5)
tempnum = 0;
else if (tempnum > 7)
tempnum = 2;
else
tempnum = 1;
That is easy but very dirty solution. I use probability a lot and sometimes I use it for more than 3 variables so this solution is not a good way. Anyone have any idea to code it cleaner?
Thanks
What is dirty about it? You have random number (pseudo random actually but random enough) and you have a probability check. Nope, sounds good to me.
Just to let you know
The Random.Range(0, 10)
will never return the result of 10, in your case, as when asking for an integer it will never return the max value. Dont know why its that way but it is.
So you should use Random.Range(0, 11);
or just change the type to a float
Also, your code seems fine to me, at least that how I would do it
Actually he should not use (0,11) or then it is no more 100% but 110% since you have value from 0 (included) to 9 -> 10 values. First gets from 0 (included) to 4 -> 5 values out of 10->50% If you include 10, it means the value above 7 is no more 20% but 30% and the other is already 30%
50 + 30 + 30 = 110%
Yes, Random.Range(0,10) is true because 0 is counted also. So no wrong part of it. It is dirty because if there are more expected percentages, then I have to write more if-else. Also if I need %13.5-%42.5 and %44, then it will be harder to control them. I have an elegant solution but it is long. Anycase, I will share it since I couldn't find a better one:
//Add how many percentage elements you want
[Range(0, 100)]
public int[] percentage;
//The result
public int tempnum = 0;
void Start ()
{
int randint = Random.Range(0, 101);
int sum = 0;
for (int i = 0; i < percentage.Length; ++i)
{
sum += percentage[i];
if (randint < sum)
{
tempnum = i;
break;
}
}
}
Your answer
Follow this Question
Related Questions
probability of child Game objects 1 Answer
How to make a random team chance? 1 Answer
Loot Drop Chance 3 Answers
How to Make Probabilties in Script? 1 Answer