How to define the range of a random value?

Let`s say i want to rotate my object to a random degree at start of frame. How do i?

Fitrst i tried this:

static var rotation : Quaternion;
function Start(){
          		transform.rotation.y=Random.rotation;
}

But then i get a Cannot convert ‘UnityEngine.Quaternion’ to ‘float’ warning.

Then i tried
transform.Rotate(0, Random.rotation,0);, which gave me a No appropriate version of ‘UnityEngine.Transform.Rotate’ for the argument list ‘(int, UnityEngine.Quaternion, int)’ was found warning.

That`s the point where i realized that a quaternion is a vector. And that it will not work that way. So next i tried to generate a random number between 0 and 360. And am totally lost now because the manual does not tell me how to set the range for the random value.

How do i define the range of a random value?

Random.Ranged( -180.0f, 180.0f - Mathf.Epsilon);

The ranged function has a poisonous overload for type-in values though, so make sure you put a decimal or f to indicate a float. Though this probably isnt a issue while that above function works, instead you’d probably want to do

Random.Ranged( -180.0f, 180.0f - Mathf.Epsilon);

the reason is the first Ranged random above could give you -180 or +180 which is the same, though its probably not a big deal…

then use the float value returend by Random.Range in your Rotate call on whichever axis

Got it to work. The solution was

transform.rotation.y=Random.Range(0,360);

Crossposting. ThanksBDev for your solution. But i think i better stick to my solution here for now. Not so much values. You named it: poisonous value overload :slight_smile:

transform.rotation.y is not degrees. transform.rotation is a quaternion, which means that the x/y/z/w values are normalized between 0 and 1. You presumably want eulerAngles, except setting just the y element is usually a bad idea; you’d want to set x/y/z all at once.

–Eric

Ah, thanks for the hint Eric. I already started to wonder why my enemies ended in facing in just one direction :slight_smile:

That one works much better:

transform.eulerAngles = Vector3(0, Random.Range(0,360), 0);

You may want to slip in a decimal point for one of the parameters to Range, not that its a big deal but you’ll only get single degree randomness there like 1, 5, 8 and not 1.3, 4.8, 7.9 because of the int / float overloads.