- Home /
using Switch and Case for 50% chance of occurance? C#
I am working on a script where 50% of the time, one event will occur (blocking) and 50% of the time, the attack will be successful. I do not think I am using switch and case correctly though, because only case 0 occurs. I cannot tell if case 1 is ever occurring, and I do not think it does.
switch(Random.Range(0, 1))
{
case 0:
audio.clip=Shieldblock;// DM I ADDED
audio.Play();// DM I ADDED
break;
case 1:
enm.currenthealth=enm.currenthealth-damage;
break;
}
Answer by DaveA · Oct 25, 2012 at 12:52 AM
if (Random.value < .5)
{
audio.clip=Shieldblock;// DM I ADDED
audio.Play();// DM I ADDED
}
else
enm.currenthealth=enm.currenthealth-damage;
Answer by Eric5h5 · Oct 25, 2012 at 12:53 AM
Random.Range (0, 1) will only ever return 0. Anyway you should just use if/else for this.
if (Random.value < 0.5f) {
// do one thing
}
else {
// do the other thing
}
Answer by Owen-Reynolds · Oct 25, 2012 at 04:35 AM
`Random.Range` using ints only goes to one less than the max value. To flip a coin 0 or 1, use `Random.Range(0,2);`
That seems odd, but in regular C# Rand(4) rolls 4 numbers: 0,1,2 and 3. So all programmers "know" you can never roll the highest.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Getting -1 or 1 randomly without including the 0 4 Answers
Trouble with Null Reference in Script 2 Answers
Non-repeating random number generator crashing unity 1 Answer