- Home /
Time.time undependable in a coroutine?
I have this script which is called from the start function as a coroutine:
function RotateBasedOnCurve(){
var animating : boolean = true;
var animStartTime : float = Time.time;
while(animating){
var localTime : float = Time.time - animStartTime;
print(localTime + " " + EquipAnimCurve.length);
tarObject.localRotation.eulerAngles.x = EquipAnimCurve.Evaluate(localTime);
if( Mathf.Approximately(localTime, EquipAnimCurve.length/2) || localTime == EquipAnimCurve.length/2){
Debug.Log("We are half way through");
}
if(localTime > EquipAnimCurve.length){
print("function over");
animating = false;
}
yield;
}
}
Note: the || is just a redundancy I put in while troubleshooting
The rotation follows the curve correctly, and the "function over" print is called, but the debug log "We are half way through" is never called. The local time prints are erratic, often skipping decimal places completely.
I am not sure what is happening here, I am new to coroutines. Is Time.time not dependable in a coroutine? And if not, how can I keep track of time inside this while loop?
Answer by Bunny83 · Jul 23, 2013 at 09:58 PM
Uhm you know that your game doesn't run infinite frames per second?`That means between two frames lies some time. For example when you have a framerate of 100 frames per sec. The time between two frames is 1/100 sec. so 10ms. Since you never have an exact constant framerate it will fluctuate from frame to frame. So one frame it takes 10.0416562 seconds the other frame it takes 9.87651321 seconds. Time.time is the time the current frame has been started. It's almost impossible to "sample" an exact time.
The best solution for such "events" is to use a boolean and a statement like this:
if( !halfWayThrough && localTime > EquipAnimCurve.length/2)
{
Debug.Log("We are half way through");
halfWayThrough = true; // prevent the event from firing twice.
}
Yeah I thought that is what $$anonymous$$athf.approximately was intended for. Thanks, got it working.
P.S. just in case anyone stumbles upon this code for some other reason, there is another mistake I made here. The length of an animation curve refers to the number of keys it has, not the length of the curve. To get the length you need:
curveName.keys[curveName.length - 1].time
That will return the time specified in the final key, which is the total time of the curve.