- Home /
How can I get a fixed time value with using Time.time?
How can I get a fixed time value out of Time.time and compare it with a defined float?
I really don´t know if I understand Time.time right, so if I something here is wrong pleas correct me...
Time.time is read only, and shows me the Time passed since my Scene started if I have it in start function.
If I want to use a Trigger to display the current Time at the triggering I do :
function OnTriggerEnter()
{
timeOnHit = Time.time;
Debug.Log("TheTimeOnTriggerHit" was: + timeOnHit);
}
3.But if I understand right my "timeOnHit" variable is not saved with the value it has at the Debug.Log because if I try to compare it to a float nothing happens:
function OnTriggerStay()
{
if(timeOnHit - Time.time >= 1.0)
{
Debug.Log("Time passed");
} }
Also this is not working in a new project on a simple cube attached:
var startTime;
var timeOnHit;
//
function Start()
{
startTime = Time.time;
}
// function OnMouseEnter()
{
timeOnHit = Time.time;
Debug.Log("TheTimeOnTriggerHit was: "+ timeOnHit);
}
//
function OnMouseDown()
{
Debug.Log("Mouse is Down");
if(startTime - timeOnHit >= 1.0)
{
Debug.Log("Time passed, IF statement executed");
}
}
Answer by Datael · Apr 04, 2012 at 03:04 PM
Try:
if(Time.time - timeOnHit >= 1.0)
The code you have currently will always render a negative number since Time.time will be greater than timeOnHit.
It's always worth Debug.Log()ing the results used in comparisons when things don't go quite as you'd expect them to; noticing that variables are the wrong way round is often an easily missed mistake and you would have soon noticed your error this time around.
It has no effect, the if statement isn´t executed...I thought that maybe something else is messed up in the Project or in Unity so I tested it in an clean new Project with the same result!! Here is the script just put it on a cube or a plane:
var startTime; var timeOnHit; // function Start() { startTime = Time.time; } // function On$$anonymous$$ouseEnter() { timeOnHit = Time.time; Debug.Log("TheTimeOnTriggerHit was: "+ timeOnHit); } // function On$$anonymous$$ouseDown() { Debug.Log("$$anonymous$$ouse is Down"); if(startTime - timeOnHit >= 1.0) { Debug.Log("Time passed, IF statement executed"); } }
Of course it won't get executed; Time.time will always be greater than the timeOnHit since it is always recorded (unless you click it in the exact same frame as you put your mouse over it) afterwards, making Time.time a larger number than timeOnHit. Therefore, the result will always be negative (except in the exact same frame case I mentioned earlier where it will be 0), and a negative number is never greater than 1, rendering the code inside the if statement unreachable. To get any comparison you're going to have to flip the variables around like I mentioned in my initial answer...