Random value for if statement

i have some code and i’m not sure on how to get a varaible into a if statement.

#pragma strict
public var number;
function Start () {
var number = Random.Range(2,2);
}

var myTimer : float = 10.0;
 
function Update () {
if (var number == 2){
transform.position.y = 9.320176;
transform.position.z = 0;
transform.position.x = 0;
}
}

First, welcome to Unity Answers :slight_smile:

Second, you have two little mistakes that are probably preventing this from compiling.

  1. If you’re using static typing (which you should) You should always declare a type with your variables (it can be inferred, but somehow the compiler needs to know what this object is). To do that you should change:

    var number;
    

    to:

     var number : int;
    
  2. You don’t need a var keyword in the if statement. You only want to put var in when you’re declaring a variable for the first time. Since you already declared it above, you don’t need to do it again. P.S. You did this twice, make sure you fix it in both places that you did it.

     if (number == 2) {
    

So your complete code should look like.

#pragma strict
public var number : int;
function Start () {
     number = Random.Range(2,2);
}
 
var myTimer : float = 10.0;
 
function Update () {
    if (number == 2){
        transform.position.y = 9.320176;
        transform.position.z = 0;
        transform.position.x = 0;
    }
}

Hi Brandon,
Couple of things :

  1. The keyword var is used to declare a variable. Where you declare it matters very, very much : declare it in a function, and the variable will only be valid in that function ( it’s called a local variable ). What you are doing there is declaring number in Start, and then in update declaring a new variable also called number, which will by default be 0.

  2. Variables should be typed. Not in JS, where the compiler will try to infer type, but if you’re learning, type your variables. var number : int; ( or float or double or whatever the type you want your number to be ).

  3. Random.Range (2,2) is not much of a range… Give me a number between 2 and 2 ? Worse, give me a number between 2 and 2, excluding 2 ? ( http://docs.unity3d.com/Documentation/ScriptReference/Random.Range.html )

Either you want to pick a random value once ( in Start ), and do something accordingly, or pick a random value every frame, and do something accordingly. Do clarify what you’re trying to achieve! Certainly not locking transform.position every frame to the same value if number == 2.

  1. transform.position is a Vector3. UnityScript ( JS ) allows you to do transform.position.x = whatever by behind the scenes replacing the line by transform.position = new Vector3 ( whatever, transform.position.y, transform.position.z );
    So you will ask 3 times less from the cpu if you directly assign a Vector3 to transform.position instead of setting x y z seperately.

Hope it helps!