1 divided by 2 = 0?

ok so as soon as i press “p” to increase the difficulty, difficulty increases to 2 and the timer sets to 0. i already tried making it a float but that didn’t change anything?

var xPos : float = Random.Range(-50,50);
var yPos : float = Random.Range(-50,50);
var zPos : float = Random.Range(69,9001);
var spawnPos : Transform;
var spawnObject : GameObject;
var timer : float = 1;
var difficulty = 1;
var score = 0;
var countScore = 1;

function Start () {
Invoke("CustomUpdate",timer);
}

function CustomUpdate () {
Invoke("CustomUpdate",timer);
xPos = Random.Range(-50,50);
yPos = Random.Range(-50,50);
zPos = Random.Range(69,9001);
spawnPos.position.x = xPos;
spawnPos.position.y = yPos;
spawnPos.position.z = zPos;
Instantiate(spawnObject,spawnPos.position,spawnPos.rotation);
if(countScore == 1){
score += 1;
}
}

function Update () {
if(Input.GetKeyDown("o")){
if(difficulty >= 2){
difficulty -= 1;
}
}
if(Input.GetKeyDown("p")){
if(difficulty <= 9){
difficulty += 1;
}
}
timer = 1 / difficulty;
}

function Message () {
countScore = 0;
}

function OnGUI () {
GUI.Label (Rect (10, 10, 200, 40),"score:" + score);
GUI.Label (Rect (10, 60, 200, 40),"difficulty" + difficulty);
}

if you are doing division with int, the result will be round down, so 1/2 is 0.5 and it will be round down to 0.

To get the 0.5:

var timer : float = 1; //You got this right    
...
//This will do, I think
   //Embarassing mistake
   timer = ( 1 * 1.0f ) / difficulty;

   //A better correction
   timer = 1.0f / difficulty;

you just have to make the 1 a float:

timer = 1.0 / difficulty;

First off you never specified difficulty as an float value. Since it had no decimal Javascript automatically makes it a Integer. With Integer values and division what happens is something called “truncating”.

Sure, it knows that 1/2 = 0.5 but that isn’t a Integer value. Ints are only concerned with the left side of the decimal. So the result is that the .5 is dropped and the 0 is returned.

Both solutions above are perfectly fine, but I also wanted to elaborate why this occurs. Be careful, this happens for all mathematical operations for ints, and ints have range of ~-2 billion something to ~2 billion something.