Search code examples
if-statementunity-game-engineruntime-error

Not respecting if statement


I have this code that is supposed to fade out the rotating yellow cube once the ball triggers the collision.
But once the alpha reaches 0, it continues one more time until the alpha reaches -0.200 and the cube becomes blue before disappearing.

if (disapear)
{
    if (rndr.material.color.a > 0.0f)
    {
        rndr.material.color -= new Color(0, 0, 0, 0.2f);
        Debug.Log(rndr.material.color);
    }
    else
    {
        gameObject.SetActive(false);
    }
}

finish line

Screenshot 2

EDIT: There is no problem for the red finish line which uses the same code.

EDIT2: On the second screenshot I managed to find the value of a before it becomes -0.200, which is 2.980232E-08. I don't really know what it means.


Solution

  • This is likely because the value of alpha when it gets close to 0f might not exactly be 0 (i.e. 0.0000001 > 0.0f), I'd make your boolean be if (rndr.material.color.a > 0.2f) or set the alpha value to 0 under else