Illogical if else statement behavior

I have the following piece of code in one of my scripts.

All it is doing is toggling a game object between visible and not visible - m_priteButtonPressed is set to a valid 2D sprite while m_spriteButtonUnpressed is null.

It is in a base class so you can alternatively set spriteButtonUnpressed to a valid 2D sprite.

When I step through it with the Monodevelop debugger both the if and the else statements are executed, i.e. m_spriteButtonrender.sprite = m_spriteButtonPressed; is executed followed by m_spriteButtonrender.sprite = m_spriteButtonUnpressed;

Now what on Earth would cause Unity to execute both statements like this???

The symptom is not just a debugger anomaly because the symptoms are that my game object never becomes visible regardless of whether the Monodevelop debugger is running or not.

    protected virtual void SetPressed(bool bPressed)
    {
        if (m_spriteButtonrender != null)
        {
            if (bPressed)
                m_spriteButtonrender.sprite = m_spriteButtonPressed;
            else
                m_spriteButtonrender.sprite = m_spriteButtonUnpressed;
        }
        else
        {
            Debug.Log("BaseButtonManager.SetPressed(bool bPressed) - m_spriteButtonrender not set...");
        }
    }

Try printing some messages to see if it’s really entering both, like this:

if (bPressed) {
m_spriteButtonrender.sprite = m_spriteButtonPressed;
Debug.Log("If condition is true");
}
else {
m_spriteButtonrender.sprite = m_spriteButtonUnpressed;
Debug.Log("If condition is false");
}

Just don’t run Unity on a quantum computer.

1 Like