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?

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

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;
}

Or you could always go:

public static int RandomSign()
{
    return UnityEngine.Random.value < 0.5f ? 1 : -1;
}

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.