- Home /
Getting -1 or 1 randomly without including the 0
I want to get the value of -1
or 1
randomly.
I know we can use Random.Range(min, max)
for this, but if I use -1
and 1
, then 0
is of course also included, which I do not want.
What simple method is there to get this right? So far I have done two different ways to overcome this problem. I used 1 and 2 for min and max, and if it's 1 then I set the value to -1, if it's something else, then I set the value to +1. The other method is to put the random into a loop, and only quit the loop if the value is not 0.
But I don't think either of these two solutions are probably a good habit to get into, especially the loop one.
Would appreciate any suggestions. Perhaps there's an altogether different method?
Answer by Bunny83 · Dec 16, 2013 at 01:57 AM
Just do this:
int someValue = Random.Range(0,2)*2-1
// Random.Range(0,2) == 0 or 1
// Random.Range(0,2)*2 == 0 or 2
// Random.Range(0,2)*2-1 == -1 or 1
Uhm I have broken down the code in the 3 comments below the code? What else should I explain?
in case of random integer the second argument is exclusive. that mean a Random.range(0,50) is a random between 0 and 49. So Random.Range(0,2) can't give you a result of 2, but only 1 or 0.
Then, it's just basic mathematics; (1 2) - 1 = 2 - 1 = 1 (0 2) - 1 = 0 -1 = -1
why is the second argument exclusiv for int and inclusiv for float ? i don't know, probably special cases of mathematics which cause errors.
Answer by KellyThomas · Dec 16, 2013 at 02:01 AM
You first suggestion is the best option, just put it in a function and forget about the implementation:
function RandomSign() {
if (Random.Range(0, 2) == 0) {
return -1;
}
return 1;
}
That won't work; Random.Range(0, 1) will always return 0.
Answer by enigma_lvn · Feb 23, 2018 at 01:32 PM
Or you could always go:
public static int RandomSign()
{
return UnityEngine.Random.value < 0.5f ? 1 : -1;
}
thankyou: I modified Your Code And, Use this : public static float RandomSign(float postValue, float negatValue) { return Random.value < 0.5f ? postValue : negatValue; }//it,s HelpFull
Answer by xandermacleod · Dec 16, 2013 at 02:01 AM
float randomFloat = Random.Range(min, max);
while(randomFloat == 0){ randomFloat = Random.Range(min, max); }
float absFloat = Mathf.Abs(randomFloat); float finalNumber = randomFloat / absFloat;
// finalNumber will be 1 or -1.
$$anonymous$$athf.Sign()
would simplify this, but it may still use a division internally.
Your answer
Follow this Question
Related Questions
Trouble with Null Reference in Script 2 Answers
Modify mesh problems 1 Answer
move gameobject into a random position and the spawn an enemy 1 Answer
Make AI walk around randomly until Player is Seen. (C#) 2 Answers
Distribute terrain in zones 3 Answers