# Help understanding timer code.

I got this code from another answer and while I understand how it works, I would like to know what 1 certain part does.

``````var gText: GUIText; // drag here the GUIText from Hierarchy view
var timer: float = 10;

function Update(){
timer -= Time.deltaTime;
if (timer < 0) timer = 0; // clamp the timer to zero
var seconds: int = timer % 60; // calculate the seconds
var minutes: int = timer / 60; // calculate the minutes
gText.text = minutes + ":" + seconds;
}
``````

timer % 60. I know that basically it wont let the timer go anywhere over 60. I don’t particularly understand why, nor do I need to since I know how to use it. Mainly I like learning everything I can now. It’s probably not even a coding function and instead a simple math function. I usually skipped my classes and it’s probably catching up to me now.

% is a remainder operator. It will divide the first number by 60, but instead of returning the answer it returns the remainder.

So this line

``````var seconds: int = timer % 60
``````

does the same thing as this

``````var temporaryVariable : int = timer;
while (temporaryVariable > 60){
temporaryVariable = temporaryVariable - 60;
}
var seconds : int = temporaryVariable ;
``````

The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators.

So basically, the minutes divide the timer by 60. So lets say we go with 125, so that means there will be 2 minutes and 5 seconds. If we just divide by 60 we get 2.083 which is obviously not 2 minutes and 5 seconds. These are ints though, so it would simply show 2 for the minutes.

Now we use the % operator for the seconds. It takes 125/60 and then displays the remainder. So for us it will be 2 with a remainder of 5. Since all it cares about is the remainder, it’s just 5.

So now lets say it’s 119. Well, 119/60 gets us 1 and some change. Now 119%60 gets us 1 with a remainder of 59. So as you can see, it’s impossible for the remainder to get above 59 before it resets back to 0 and gets another minute.

…that’s modulo… Let’s say you have 320 seconds and you want to display them as minutes:seconds. If you divided 320 it would be like this: 320/60 = 5 (so 5 minutes) and 320%60 = 20 (so 20 seconds).

Basically “/” gives the exact part of the division, while “%” gives what remains after dividing exactly.