- Home /
Random range choosing both results?
I am trying to work out why when this script runs, it spawns both objects? Sounds silly, but I was trying to spawn one or the other, well, eventually many, but in this example just one. When it runs both objects appear.
var randomNumber : int;
var floorTileNorm : GameObject;
function Start () {
randomNumber = Random.Range(1, 2);
if (randomNumber == 1);
Instantiate (floorTileNorm, Vector3(100,200,100),Quaternion.identity);
}
if (randomNumber == 2);
Instantiate (floorTileNorm, Vector3(400,200,100),Quaternion.identity);
Thanks for taking a look.
Thank you both very much for the swift answer, which is correct. I have amended the code and it works.
Robertbu - I didn't use your code or an 'else' because I will be making the range much bigger, it is for use generating a 'random' floor tile position at the start of the game. It's something I literally decided to look at today. Could you please explain to me why the use of <0.5? If I understand what you are saying, then the last number is redundant, hence it would always be a '1'. But if the range is say 4, but I have 3 options, that would be fine right?
nicolasjr - thanks for that, your answer is also correct. I don't know how to make them both right answers :D
It works great now, time to write loads more options.
Random.value returns a value between 0 and 1, so < 0.5 happens half the time. For many choices, you might want a case statement:
switch (Random.Range(1,5) {
case 1:
//Do whatever for 1
break;
case 2:
//Do whatever for 2
break;
case 3:
//Do whatever for 3
break;
case 4:
//Do whatever for 4
break;
}
Answer by robertbu · Apr 12, 2014 at 09:48 PM
You have two problems here. The first is the structure of your code. On line 8, you have a ';' at the end of your 'if' statement which terminates the 'if'. In addition, your '}' on line 11, closes off the 'Start()' function. The reason you get the second one is that your other code gets executed because of the way Javascript handles scripts in open code.
Another problem is that Random.Range() when used with integers is exclusive of the last number, therefore your code would only return 1...never 2. You may one something more like:
#pragma strict
var randomNumber : int;
var floorTileNorm : GameObject;
function Start () {
if (Random.value < 0.5) {
Instantiate (floorTileNorm, Vector3(100,200,100),Quaternion.identity);
}
else {
Instantiate (floorTileNorm, Vector3(400,200,100),Quaternion.identity);
}
}
Answer by nicolasjr · Apr 12, 2014 at 09:48 PM
The problem is that you're using " ; " after the if statements, so, it's not interpreting that the above lines are about the statement.
So, it's really instantiating both objects. Just remove the " ; " from after if, and you'll be good to go. :)