The question is answered, right answer was accepted
HELP! How to use a timer to set variables?
Hello again. This problem has been bugging me in every scene I try to make. So basically I have a timer variable(a float) and any other variable(an int or bool). So what i want to do is based on the value my timer variable has, the value of another variable will change. Example "if(timer >= 10.0f){ goal = true; }" or something like that. Here's some of my code and a screenshot of what I mean to further explain(also ignore the missing script error, that's for something else):
public int posNum;
public float cameraTimer;
public bool isIdle = true;
public bool isViewing = false;
// Update is called once per frame
void Update () {
cameraTimer += Time.deltaTime;
if(isIdle){
//Sets camera position number
if(cameraTimer == 0.1f){
posNum = 0;
}else if(cameraTimer == 8.2f){
posNum = 1;
}else if(cameraTimer == 16.1f){
posNum = 2;
}
IdleCam();
}
if(isViewing){
}
}
As you can see the cameraTimer has passed 8.2f and the camPos variable has not been set to 1. How do I fix this? Thanks.
Answer by jmonasterio · Dec 28, 2015 at 04:06 PM
The timer will never be exactly equal to 0.1f, 8.2f, and 16.2f. Comparing floats with == is a bad idea, since the floating point value may be off by a tiny amount like 0.1001. Especially with timers, the time doesn't go up by a fixed amount, so it will almost never ever be equal.
Use: >=
Like:
if(cameraTimer >= 0.1f){
posNum = 0;
}else if(cameraTimer >= 8.2f){
posNum = 1;
}else if(cameraTimer >= 16.1f){
posNum = 2;
}
Thanks for the answer. But heres a followup question: Could I do something like: if(cameraTimer > 0.1f &&& cameraTimer <8.1f){ posNum = 0; }
I don't know if that's correct. What I'm trying to say could I do an IF statement where the float variable has to be between a certain range of values. Thanks again.
You could put the code in different order and it would do what you want without so many &&'s.
if(cameraTimer >= 16.1f){
posNum = 2;
}else if(cameraTimer >= 8.2f){
posNum = 1;
}
else if(cameraTimer >= 0.1f){
posNum = 0;
Answer by Priyanshu · Dec 28, 2015 at 04:06 PM
To check your mistake, simple print cameraTimer value in Update. By doing this you can see that cameraTimer will never be equal to .1/8.2/16.1 but equivalent to values like .12345/ 8.2323/16.12343.
Therefore its more feasible to use greater Than or Less Than operators. for such purpose.