system
1
Under a similar note to my other question at http://answers.unity3d.com/questions/18765/how-do-i-format-a-string-into-daysminuteshoursseconds I'd like to know how excatly I should use the % operator.
I need to calculate days,hours,minutes and seconds. So far I have..
displaySeconds= seconds % 60;
displayMinutes =seconds /60;
..but I got this from an example and I've no idea what th % is doing or how to go from here to get days/hours.
Many thanks!
displaySeconds = seconds % 60;
This shows you the "remainder" of seconds / 60
e.g.
120 seconds / 60 would be equal to 2 with 0 remainder
or
121 seconds / 60 would be equal to 2.01666667 or 2 and 1 remainder
What that script does is tell you how many seconds you should display on a clock i.e. if the time was 2 seconds you'd display 2 seconds, if the time was 62 seconds you'd display 2 seconds as well.
The minutes part of the script is pretty straight forward, there are 60 seconds in a minute...
EDIT:
Similarly for days and hours, if you know how many seconds there are in an hour (3,600) and how many seconds in a day (86,400) You can calculate those using the same formula.
e.g.
displaySeconds = seconds % 60;
displayMinutes = (seconds / 60) % 60;
displayHours = (seconds / 3600) % 24;
displayDays = seconds / 86400;
I went and did an example JS:
var displaySeconds : int;
var displayMinutes : int;
var displayHours : int;
var displayDays : int;
var seconds : float;
function Update () {
seconds = Time.time;
displaySeconds = seconds % 60;
displayMinutes = (seconds / 60) % 60;
displayHours = (seconds / 3600) % 24;
displayDays = seconds / 86400;
}
function OnGUI(){
GUI.Label(Rect(0,0,200,30),"Time " + displayDays + " : " + displayHours + " : " + displayMinutes + " : " + displaySeconds);
}
This will display the time since the program started in Days : Hours : Minutes : Seconds
Just swap out Time.time for whatever system you want to have shown in your game (game-time probably)
Edy
3
var seconds : int = 12345;
displaySeconds = seconds % 60;
displayMinutes = seconds / 60;
It's very important the seconds variable to be int, otherwise the displayMinutes variable would receive a float value.