- Home /
Generate random number per function call?
Hey guys!
I'm trying to simply generate a random number. (either 1 or 2) and use that random number to choice a different "if condition".
What I've got works, but only chooses the number 1 every time.
here's what I have;
function Death ()
{
speed = 0.0;
var deathChoice = Random.Range (0, 2);
if ( deathChoice == 1 )
{
print ( deathChoice );
animation.Play("Death01");
yield WaitForSeconds (1);
Destroy (gameObject);
}
if ( deathChoice == 2 )
{
print ( deathChoice );
animation.Play("Death02");
yield WaitForSeconds (1);
Destroy (gameObject);
}
}
Answer by Ejlersen · Nov 05, 2013 at 06:03 PM
In the documentation, it says that Random.Range(int,int) is where minimum is inclusive and maximum is exclusive. So, if you want it to give a random number of either 1 or 2, then it should be:
Random.Range(1, 3);
I changed the Random.Range as you suggested, and now it appears to play both if statements at the same time. How could I alter this function to chose to play either one condition or the other?
Tried altering code to this but it still seems to play both conditions, (rolling the dies on every frame so to speak) until the object is destroyed.
function Death ()
{
speed = 0.0;
var deathChoice = Random.Range (1, 3);
var isDying = true;
if (isDying)
{
if ( deathChoice == 1 )
{
isDying = false;
print ( deathChoice );
animation.Play("Death01");
yield WaitForSeconds (1);
Destroy (gameObject);
}
if ( deathChoice == 2 )
{
isDying = false;
print ( deathChoice );
animation.Play("Death02");
yield WaitForSeconds (1);
Destroy (gameObject);
}
}
}
The chances are fifty to fifty. Also you can always get the first animation even if the possibility of it is % 99. Larger the range and debug what random numbers you get. İts just a bad luck that you are always hitting the first animation.
The thing is that I put a print command in each if statement, and each print commands fires off every time.
Your answer

Follow this Question
Related Questions
Random.Range Spawner 1 Answer
LocalEulerAngles with random rotation doesn't work 1 Answer
Have random.range anims access float speed variable 0 Answers
Color GUILayout Buttons from Array of Colors (C#) 2 Answers
randomize a function from a array (C#) 3 Answers