Random Values

Hi,

I’m currently using this script to move objects:

var moveX = 5.0;
var moveY = 5.0;

function Update () {
    transform.Translate(moveX*Time.deltaTime, 0, 0);
    transform.Translate(0, moveY*Time.deltaTime, 0);
}

Is there anyway to generate random values for the variables between two numbers?

e.g Between -60 and 60?

Thanks,
Stuart

Take a look at the Random class in .NET library.

Looks like you’ll want something like:

var rand = Random();
random_number = rand.Next(121) - 60;

UPDATE:

I’ve figured out this script:

function Update () {
    transform.Translate(Random.Range(-60, 60)*Time.deltaTime, 0, 0);
    transform.Translate(0, Random.Range(-60, 60)*Time.deltaTime, 0);
}

But this changes the speed of movement every frame when I just want it to decide on a speed and stick with it.

Any ideas?

Thanks,
Stuart

Opps, sorry Timmer I was writing a reply just as you posted.
Any ideas for my update?

My latest attempt is:

var speed1 = Random.Range(-60, 60);
var speed2 = Random.Range(-60, 60);

function Update () {
    transform.Translate(speed1*Time.deltaTime, 0, 0);
    transform.Translate(0, speed2*Time.deltaTime, 0);
}

But this just chooses a value and sticks with it.
I want the script to generate a new value every time the level loads.

The following doesn’t work either:

function OnLevelWasLoaded () {
var speed1 = Random.Range(-60, 60);
var speed2 = Random.Range(-60, 60);
}
function Update () {
    transform.Translate(speed1*Time.deltaTime, 0, 0);
    transform.Translate(0, speed2*Time.deltaTime, 0);
}

I get an error because the transform.Translate can’t find the var’s in a different function.

Thanks,
Stuart

If the object containing the script isn’t persistant through level loading, you can just place the random call in the Start or Awake functions. That way it will get called and randomised on each load.

Thanks for the reply.
But I’m still getting the same “Unknown Identifier” error.
I think because it’s in a different function… Maybe.

You need to declare the variables outside of the function, but set the values inside. Something like this:

var speed1 : float;
var speed2 : float;

function OnLevelWasLoaded () {
    speed1 = Random.Range(-60, 60);
    speed2 = Random.Range(-60, 60);
}

function Update () {
    transform.Translate(speed1*Time.deltaTime, 0, 0);
    transform.Translate(0, speed2*Time.deltaTime, 0);
}

Thanks but when I use that script all my objects just stay still?
With the values 0 0 in the editor.

Are you sure you need OnLevelWasLoaded for this? Try putting the same code inside the Start function. (Also, just FYI, OnLevelWasLoaded should be declared with an integer parameter - see here.)

Thanks andeeee that worked perfectly. :smile: