- Home /
Making a sped up timer in unity
im trying to make a timer which shows minutes and hours, but not by real time, but by sped up time instead, i know it sounds confusing but maybe my code will make it clearer
public class Clock : MonoBehaviour {
public float DayCycleInMinutes = 2;
public float dayCycleInSeconds = dayCycleInMinutes * 60;
private float minuteInGameTime = dayCycleInSeconds / 24 / 60;
private float hourInGameTime = dayCycleInSeconds / 24;
private float seconds = 0.0f;
public void Update(){
seconds += Time.deltaTime;
if(seconds >= minuteInGameTime){
minuteInGameTime += 1;
seconds = 0;
}
if (minuteInGameTime >= 60)
hourInGameTime += 1;
minuteInGameTime = 0;
guiText.text = ("Minutes: " + minuteInGameTime + " " + "Hour" + hourInGameTime);
}
i get a compiler error, and im not really sure why. if someone can fix the code it will be great, and if someone can also explain what is the problem it will be fantastic. thank you in advance.
Answer by robertbu · Sep 18, 2014 at 04:45 PM
For future compiler error questions, please include a copy of the error messages taken directly from the console.
You are missing the closing brace on the class, 'DayCycleInMinutes' is used with both an upper and a lower case 'D', and you need to do your initialization in Start() for this code. Here is the result:
using UnityEngine;
using System.Collections;
public class Clock : MonoBehaviour {
public float dayCycleInMinutes = 2;
public float dayCycleInSeconds;
private float minuteInGameTime;
private float hourInGameTime;
private float seconds = 0.0f;
void Start() {
dayCycleInSeconds = dayCycleInMinutes * 60;
minuteInGameTime = dayCycleInSeconds / 24 / 60;
hourInGameTime = dayCycleInSeconds / 24;
}
void Update(){
seconds += Time.deltaTime;
if(seconds >= minuteInGameTime){
minuteInGameTime += 1;
seconds = 0;
}
if (minuteInGameTime >= 60)
hourInGameTime += 1;
minuteInGameTime = 0;
guiText.text = ("Minutes: " + minuteInGameTime + " " + "Hour" + hourInGameTime);
}
}
Well it compiles now but it still doesn't work, just stuck on 5 hours
You need to put some Debug.Log() statements in and watch the flow. I believe line 26 should be inside the 'if' statement on line 24:
if ($$anonymous$$uteInGameTime >= 60) {
hourInGameTime += 1;
$$anonymous$$uteInGameTime = 0;
}
well there we fixed another problem, but the hour is still stuck on 5. i checked in debug.log() and it seems it sets hourInGameTime to the right number, and then to 5, going back and forth every second, which is odd. i will try to solve this and pay more attention in the future to my syntax and such. thank you so much for the time you spent on helping me!
Your answer
Follow this Question
Related Questions
Problem with Snake Game(input help) 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity Countdown timer in C# 1 Answer
GUI elements vanish when publishing 1 Answer