- Home /
Questions about a random value between two numbers
Okay, basically I have three questions.
Say I want to make a "speed" variable of type "float" to be a value between 10 and 15. What is the formatting for this?
If the script with this variable were attached to a prefab, would every instance of that prefab have a different "speed" value?
How would this randomization work? Like, what values would be selected? Would it just choose 10, 11, 12, 13, 14, and 15? Or would there be 10.5, 11, 11.5, 12, etc? Or would it go into even smaller numbers? Would there be a value of, say, 14.56783429?
Hopefully this is clear enough. Let me know if I need to clarify anything.
Answer by Eric5h5 · Jul 28, 2014 at 05:16 PM
var speed = Random.Range (10.0, 15.0);
Yes.
It chooses any float value between 10.0 and 15.0. If you want whole numbers, then use integers instead of floats (in which case the upper value is exclusive; look up Random.Range in the docs).
Thanks for the quick response! Your formatting makes sense to me, but Unity doesn't like it. Here is my simple script for moving a gameobject.
using UnityEngine;
using System.Collections;
public class $$anonymous$$over : $$anonymous$$onoBehaviour
{
public float speed = Random.Range(10.0, 15.0);
void Start ()
{
rigidbody.velocity = transform.forward * speed;
}
}
Resulting in
Assets/Scripts/$$anonymous$$over.cs(6,37): error CS1502: The best overloaded method match for UnityEngine.Random.Range(float, float)' has some invalid arguments and Assets/Scripts/$$anonymous$$over.cs(6,37): error CS1503: Argument
#1' cannot convert double' expression to type
float'
Answer by _ADN_ · Jul 28, 2014 at 05:28 PM
1 - Random.Range : http://docs.unity3d.com/ScriptReference/Random.Range.html
2 - Yes, umless you make a static variable and just access it in every monovehabiour.
3 - Will be xx,xxxxx. If you want, you can round to decimals, example:
2 decimals Mathf.Round(yourFloat * 100f) / 100f; in this case value will be x.xx;
3 decimals Mathf.Round(yourFloat * 1000f) / 1000f; in this case value will be x.xxx;
Your answer
Follow this Question
Related Questions
Make String Update for Value (GUI) 1 Answer
zero is not zero 2 Answers
Random value for if statement 2 Answers
Assign a random value to var personality" upon asset creation (Java) 1 Answer
Slider value not working? 0 Answers