I’m working on a C# script which counts and records the amount of time the player has spent in the game from the start of the game to the end. The script uses three major float variables:
- timer - used as a temp variable for counting game time
- finishTime - time when player finishes game. used for comparison purposes
- bestTime - best time player has received when playing the game. Aquired from PlayerPrefs value. Used for comparision purposes
The script in question is supposed to do the following:
- count time upwards in seconds
- when the game is finished, set the value of the finishedTime to the value of timer
- compare bestTime to finishTime: if finishTime > bestTime, bestTime = finishTime
- save bestTime using PlayerPrefs
- convert finishTime, bestTime into strings using the H:MM:SS format
- send strings to game objects with GUIText components to display strings on game over screen
For reference, this is the main block of code giving me trouble:
void SaveBestTime() {
finishTime = timer;
//only save best time if previous time has been surpassed
if (finishTime > bestFinishTime) {
bestFinishTime = finishTime;
PlayerPrefs.SetFloat("bestTime", bestFinishTime);
}
}
Currently, I’m having problems converting the finishTime and bestTime into a H:MM:SS format, as well as sending the strings to the GUIText objects. I’m not sure what to do when converting seconds into minutes and hours. The reason I didn’t convert the time when counting it was that I needed the timer value to be set for the finishTime value for comparing between that and the bestTime values. I also would need to convert the bestTime value into a string with the H:MM:SS format regardless of the situation.
The game objects I mentioned before are deactivated when the game starts (i.e. they’re grayed out in the Hierarchy), and I’m receiving NullReferenceExceptions. I’m not sure if these facts are related, but I would like some clarification regardless.
If anyone could help me out with both of these issues above, the aid would much appreciate it. Thank you for taking the time to read this question.