- Home /
Something wrong with TimedeltaTime
I changed the command several times but nothing happens.
function Update(){
if (bar == false){
currlife = 100;
}
else
currlife -= 1.0 * Time.deltaTime;
}
Tried: currlife -= Time.deltaTime * 0.1;
currlife -= Time.deltaTime;
What do you believe is wrong? BTW No need to multiply by 1.0.
Answer by aldonaletto · May 26, 2011 at 10:32 PM
RenatoB, I tested your script and it really runs fast like a crazy horse! The problem is the type of the currlife var: if you don't specify the type, javascript will do it for you, right or wrong! That's a golden rule in unity's javascript: always define the type of any var. When javascript finds an untyped variable, it must decide at runtime which's the type of its contents; it wastes CPU time and may generate errors. I fixed your script and there it goes:
var bar: boolean; var maxlife: float = 100; var currlife: float = 100;
function Start(){ bar = false; }
function Update(){ if (bar == false){ currlife = 100; } else { currlife -= 1.0 * Time.deltaTime; } }
function OnTriggerEnter(){ bar = true; }
function OnTriggerExit(){ bar = false; }
That's not correct...if you don't define the type of a variable, the compiler figures it out from the value you supply. "`var foo = 5;`" is exactly the same as "`var foo : int = 5;`". Likewise, "`var currlife = 100.0`" is the same as "`var currlife : float = 100`". This happens when the script is compiled, not at runtime. It's called type inference, and C# does this too.
C# doesn't guess the types, which is part of the confusion when people go back and forth. In C#, in float T = 0;
, the 0 is a shortcut for 0.0 and T is still a float. C#-users get in the habit of not putting ".0" on the end of floats. For fun, int T = 4.0;
is an error -- 4.0 isn't an int.
@Owen Reynolds: no, "`var t = 0.0;`" is valid C#. It works the same way. (Although in this case t would be a double, rather than a single like it would be in JS. Using 0.0f would make it a single.) The difference is that you can only do that with local variables in C#, not global.
I tested it and you both are right: Unity's javascript actually uses type inference. That's different from the interpreted javascript found in browsers, where all variables are variant types which can hold any type known.
Yeah, Javascript in Unity has almost nothing to do with Javascript in web browsers. It's way more like JScript.NET, or ActionScript 3.
Answer by DaveA · May 26, 2011 at 07:30 PM
You might want to be sure that currlife is a float when you declare it:
curlife : float = 100.0;
Answer by flaviusxvii · May 26, 2011 at 07:29 PM
There is nothing wrong with Time.deltaTime. Check your stuff again.
Answer by homeros · May 26, 2011 at 07:34 PM
Did you try using it outside of else? The problem amybe bar never becomes true.