I'm trying to make an element (3D object or UI element) blink in such way:
- There is a timer which counts down 10.0f seconds to 0.0f.
- In 10.0f to 9.9f range the object should fade out from opacity 1 to 0.
- In 9.9f to 9.8f range the object should fade back in from 0 to 1.
- Then wait 300ms.
- Then repeat and finally fade out and disappear completely on last 1.0f to 0.0f.
I created a function in Unity:
void Update(){
if ( myTimeVariable < 10.0f && myTimeVariable > 9.9f ) {
gameObject.GetComponent<Renderer>().material.color.a = (10.0f - myTimeVariable);
} else if() {
// The logic continues and makes a long set of
// else if statements to cover all times.
}
}
(It's originally a coroutine that executes after each Update()
but here it's shown otherwise for simplicity reasons.)
The problem I'm facing is that at 60 FPS I have these frames available:
0ms 16ms 33ms 50ms 66ms 83ms 100ms
And on 30 FPS I may have only these:
0ms 33ms 66ms 100ms
On 30 FPS opacity is changing this way: First I get fully opaque object on 0ms frame. Then on 33ms frame I get 0.67 opaque object. Then on 66ms frame I get 0.34 opaque object and frame 100ms doesn't belong to "fade out" if statement but fading in starts. Object starts to fade in from 0.34 to 1 over the next 100ms even if it never had 0 opacity state.
It seems that my method of making blinking object is flawed. It never reaches 0 opacity and it's very visible in the game that the last state was 0.34 opacity and not 0. Is there a way to make that blinking be certain to go to 0 opacity regardless of frame rate?
Edit: For "fade in" I only call Unity's CrossFadeAlpha()
once. That's why it starts from 0.34 and goes to 1 but even if I changed that to the other method still my frames may be available at 80ms and then 120ms and opacity 0.2 -> 0.2 is the result (never desired 0).
Time.time
to preparemyTimeVariable
. 10.0f is 10 seconds regardless of FPS. \$\endgroup\$myTimeVariable
but I assume you just wantmyTimeVariable += Time.deltaTime
\$\endgroup\$