I am fairly new to javascript and programming. I want to try something simple and heck even a timer is giving me trouble. After googling and searching I feel I can get more direct help from the pros here.
Here is my code:
var minutes = 5;
var seconds = 59;
function Update () {
seconds -= Time.deltaTime;
}
function OnGUI () {
guiText.text = minutes + " " + ":" + " " + seconds;
}
The code is attach to a gui Text, the format is correct, however the timer counts down like a rocket, took about 2 sec to count down 59 sec. I tried Time.deltaTime * 1, I tried using Time.time etc. Nothing works the way I need it to be.
Also I got this error to go with it.
ArgumentException: get_time can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don’t use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
TimerCounter…ctor () (at Assets/Scripts/TimerCounter.js:3)
Head Explodes <<
Anyone here can help a noob out?
The main problem is that you’re defining “seconds” as an integer. Time.deltaTime is a float, probably something like .01-ish or thereabouts, so subtracting .01 from 59, since 59 is an integer, results in 58. You need to either explicitly specify “float” when defining seconds, or use a float value like 59.0, so Unity knows you want it to be a float.
However, unless you actually need fractions of a second, you may prefer to avoid floats altogether and just subtract 1 every second, like so:
var seconds = 59;
function Start () {
InvokeRepeating ("Countdown", 1.0, 1.0);
}
function Countdown () {
--seconds;
}
function Update () {
// Note that you don't need each character added separately.
// Also, OnGUI is for UnityGUI functions like GUI.Label, GUI.Box, etc., not for GUIText,
// which is a component on a GameObject.
guiText.text = minutes + " : " + seconds;
}
As far as the error, I think it must be from something else, since the code you posted is technically OK even if it didn’t do what you wanted.
–Eric
Once I apply this, it slows down the android a lot. I will try to see if something else is causing the problem.