Are there better ways to create random behavior?

Hello,

I’m just getting my feet wet with Unity and following some tutorials to get a grasp of the basics. I’m currently coding a “ball” object to start at random. I’ve successfully done so but was wondering if there is a better or more concise code to achieve the same effect or even better randomize the object’s behavior. The current code:

``````function GoBall () {
var randomNumber = Random.Range(0, 14);
if (randomNumber <= 0.5) {
}
else if (randomNumber <= 1) {
}
else if (randomNumber <= 2) {
}
else if (randomNumber <= 3) {
}
else if (randomNumber <= 4) {
}
else if (randomNumber <= 5) {
}
else if (randomNumber <= 6) {
}
else if (randomNumber <= 7) {
}
else if (randomNumber <= 8) {
}
else if (randomNumber <= 9) {
}
else if (randomNumber <= 10) {
}
else if (randomNumber <= 11) {
}
else if (randomNumber <= 12) {
}
else if (randomNumber <= 13) {
}
else {
}
``````

Thanks for any help!

If you want a random direction and speed, you can do:

`````` rigidbody2D.AddForce(Random.InsideUnitCircle * maxSpeed);
``````

If you want a random direction and fixed speed you can do:

``````rigidbody2D.AddForce(Random.InsideUnitCircle.normalized * ballSpeed);
``````

Note that Random.Range() using integers is exclusive of the final value, so Random.Range(0, 14) produces the values 0 through 13, but not 14. It also only produces integers. This means that your final ‘else’ would never be executed. For what you are doing, use the floating point version:

``````var randomNumber = Random.Range(0.0, 14.0);
``````

This will produce the full range of values.

If you want these specific values but different/simpler code, you’s either have to 1) find a pattern, 2) put the values in an array, or 3) use some sort of curve to fit the values.