Hi, everyone
I have a little problem with my code. My code is about doing an action after certain amount of time…
Here is the code:
public float T = 5.0f;
void Update () {
if( Time.time == T)
{
anAction();
}
}
So the problem is that after 5 seconds, the wanted action not working!
Is the code correct or not, or it is missing something?
Please help me…
Thank you all for your time, Regards.
The problem is that Time.time is basically never going to be exactly 5. It’s going to go from 4.97 to 5.02 (or something) every time you run the game.
This is a problem you will have with nearly any float-type variable - for example, you shouldn’t check (transform.position.x == 5f) for the same reason - it’ll never be exactly that (unless it was explicitly set to exactly that value somewhere else).
So what you want here is to see if it has passed that time, but then only run the action once. Use a boolean flag to handle that.
public float T = 5.0f;
private bool hasTriggered=false;
void Update() {
if (Time.time >= T !hasTriggered) {
anAction();
hasTriggered=true;
}
}
I got it working! 
I used Greater than or equal to and it just worked perfectly!
BUT i still don’t understand why it didn’t work with == 
Thanks a lot StarManta for the help, you answered it!
i was working on it for 5 hours, anyway it was a good experience while i was trying to figure out the problem!