I discovered something interesting this evening while playing around with some sample code for an upcoming lesson. I was using InvokeRepeating() to instantiate game objects over time and noticed that even though I was using Random.Range() the game objects kept coming up in specific spaces.
Some people might be thinking, “You need to use Random.seed()!” — and I did that, but the weirdness kept happening.
Looking at the documentation for Random.Range I saw this:
public static function Range(min: float, max: float): float;
So I knew I needed to pass in two floats and I’d get a float back. The code I was using looked like this:
var x : float;
x = Random.Range(-6, 6);
I was under the impression that if Random.Range wanted floats it would give me an error if I gave it the wrong thing (no error happened) or it would automatically treat what I gave it as a float.
But when I used Debug.Log to see what my x value was being set at, I saw it was always an integer. Which was interesting, but wasn’t quite what I expected. I ended up tweaking the parameters passed to the API like this:
x = Random.Range(-6.0, 6.0);
By simply adding a .0 to the end of the numbers Unity now saw them as floats and started passing back floating point numbers to give me the effect I was after.
x = Random.Range(-6f, 6f);
Both ways seems to work for me, and if I ever want an integer to be returned from Random.Range, now I now how to accomplish that, too!
For more info: http://docs.unity3d.com/ScriptReference/Random.Range.html