- Home /
Duplicate Question
Add 1 Per Second to an Int
For some reason I can't get this to work right even though the logic seems sound.
I have a GUI box that scales down proportionally based on how much of one int there is versus another. It looks like this:
var current : int;
var maximum : int;
function Start (){
maximum = 100;
current = maximum;
}
function OnGUI (){
GUI.Box(new Rect(10,10 + Screen.height / 24,(Screen.width * current / maximum / 2), Screen.height / 24));
if(GUI.Button(new Rect(Screen.width / 8, Screen.height / 4, Screen.width / 16, Screen.width / 16), "Subtract"))
{
current -= 10;
}
}
function Update () {
if(current < maximum)
{
current += Time.deltaTime;
}
}
My problem is that it either does not work at all and adds nothing after the current amount is subtracted, or it adds too fast and goes back completely in less than a second or two. I only want the amount to change once per second. (Note that this is code I wrote just this moment as a quick demonstration of what is happening, the full code is too long to post, but the mechanics aren't changed).
use Invoke() and InvokeRepeating() for simple timers in Unity. it's that easy. unityGE$$anonymous$$S.com
Answer by PAEvenson · Jun 03, 2013 at 03:03 AM
Time.deltaTime is a float and current is an int. Ints will always round down. Can you not use a float for some reason?
or you can multiply Time.deltaTime * 100. You will lose the remainder....but it will move the decimal place over so 100 == 1 second.
$$anonymous$$ultiplying it by 100 won't work because while Time.deltaTime is a float, it is still >1, so multiplying it by 100 will not work.
I'd love to not use a float but the point is for current to go up by 1 per SECOND, it's a ti$$anonymous$$g thing, and unfortunately the only way to get time accurately is with Time.deltaTime.
Why don't you just use 'Time.time' and round it?
If you want the number of full seconds between two points in time, first cache 'Time.time' in a float variable at the beginning of the period, then every frame the number of full seconds will be
$$anonymous$$athf.FloorToInt(Time.time - startTime);
Ahh i see the issue. You may want something like this(not tested):
var timer:float = 0.0f;
function Update () {
if(current < maximum)
{
timer += Time.deltaTime;
if(timer > 1.0f)
{
current += 1;
timer -= 1.0f;
}
}
That works, took me a little bit to understand why but it does. Thanks!