Color never mets required value

Hello there i have a code that is like:

public Color color1 ;
    public Color color2;
    public float duration = 10f;

void Start()
    {

        color1 = UnityEngine.Random.ColorHSV();
        color2 = UnityEngine.Random.ColorHSV();
}

    void Update()
    {
        if (mCam.backgroundColor == color2)
        {
            color1 = UnityEngine.Random.ColorHSV();
        }
        if (mCam.backgroundColor == color1)
        {
            color2 = UnityEngine.Random.ColorHSV();
        }

        float t = Mathf.PingPong(Time.time, duration) / duration;
        mCam.backgroundColor = Color.Lerp(color1, color2, t);
}

which supposed to shift colors slowly until reaching one of the needed colors, problem is it never registers the needed color thus the ifs does not activate.

Unless you precisely stop t == 0 or t == 1, the background color will never precisely equal color1 or color2.

Don’t compare the color. Instead make the decision based on the Time, and do your own time advancement and ping pong, and when it flips to the other direction, rechoose your random color…

You are also not supposed to call Time.time every frame like that, according to the documentation.

I quote:

“Regular (per frame) calls should be avoided: Time.time is intended to supply the length of time the application has been running for, and not the time per frame.”

Usage in Mathf.PingPong is actually an acceptable usage of Time.time (and their example code for PingPong is actually exactly this). That warning in Time.time’s documentation is not precisely phrased enough - it ought to say that accumulating calls to Time.time should be avoided in Update. I can think of a dozen scenarios where it’s appropriate to use Time.time in Update, with the thing those scenarios have in common being that they all use the absolute value of Time.time, never adding it frame-over-frame, which would of course result in a nonsensical value.

The advice before that is spot-on and the best way to solve the problem, though.

Thank you guys! I did made it on based on time like you said and it works wonders!

1 Like