- Home /
How to generate a Random Float Variable
Hello I need to Generate a Random Float Variable not Int here is what I got so far.
var number = Random.value (0,3);
Answer by Eno-Khaon · Jul 04, 2016 at 04:16 AM
You're on the right track, but there are a few changes needed to make this work the way you seem to be hoping for.
First, your intent would be better represented using Random.Range(). With that in mind, there are two variations of that function. One returns an integer if both arguments are integers and one returns a float if both arguments are floating point numbers.
For convenience and computational simplicity, a number represented without a decimal place will be treated as an integer, while a number with a decimal place will be treated as a float or double (depending on language, in the case of Unity).
All in all, this means that the change to make it work for you will be very simple:
// JS
var number: float = Random.Range(0.0, 3.0);
// C#
float number = Random.Range(0.0f, 3.0f);
By representing both function arguments as floating point values, the overloaded function to return a float will be selected between the two. As a result, you will see any decimal value between 0 and 3 as your return value rather than only seeing 0, 1, and 2.
Edit: Added an explicit type to the Unityscript variant.
Answer by bugmagnet · Jul 04, 2016 at 04:11 AM
try
float number = Random.Range (0f, 3f);
The docs are your friend: https://docs.unity3d.com/ScriptReference/Random.html
Answer by tanoshimi · Jul 04, 2016 at 06:44 AM
Close, but value
is a property of the Random class not a method, so you don't need the brackets.
var number = Random.value;
That will give a number between 0.0 and 1.0, which you can then multiply by 3 (or any other value).
Answer by AmirBraham · Jul 04, 2016 at 01:32 PM
Hi , Try using Random.Range
. It takes to arguments , A min and max . In your case , It will be something like this : Random.Range(0f, 3.0f)