Random.Range question

Hello Unity I have a question considering the Random.Range. I have a random.range set for -1, 2. This will give me any of the three values: -1,0,1.
However, I do not want to get the value of zero. I just want to get a random number of -1 or 1.

var speed1 : float = 4;
[i]var rotateSpeed : float = 10;
private var zDirection : int = 1;

function Start () {
	InvokeRepeating("ChangezDirection",10, 1);
}

function ChangezDirection () {[/i]
	[b][color=green]zDirection = Random.Range (-1, 2);[/color][/b]
[i]}

function Update () {
	
	if(!Physics.Raycast(transform.position, transform.forward, 5)) {
		transform.Translate(Vector3.forward * Time.smoothDeltaTime * speed1);
	}else{
		if(Physics.Raycast(transform.position, -transform.right, 10)) {
			zDirection = 1;
		}else if(Physics.Raycast(transform.position, transform.right, 10)) {
			zDirection = -1;
		}
		transform.Rotate(Vector3.up, 90 *  rotateSpeed * Time.smoothDeltaTime * zDirection);
	}
	
	print(zDirection.ToString());
}[/i]

How do I go about getting rid of the random zero, and just getting the -1 or 1. In the script I am just asking for the random number every second, instead of every frame. So every second I get a random number of -1, 0, or 1. I want to only be getting -1, or 1.

How do I do a random range between two numbers like -1 or 1?

I guess you could just take a Random.Range (0,1) and then if 0 return -1.

zDirection = Random.value<.5? -1 : 1;

// or

zDirection = Random.Range(0, 2)*2-1;

That will only ever be 0, since the upper bound is exclusive (for ints).

–Eric

nevermind eric posted it already :frowning:

Thanks guys ended up using the second one that eric posted, since I did not understand what the first was doing.

zDirection = Random.Range(0, 2)*2-1;

The first one uses a ternary operator. It basically allows you to embed an if/else statement into a variable assignment. It’s equivalent to:

if (Random.value < .5) {
    zDirection = -1;
}
else {
    zDirection = 1;
}

–Eric