Switch-Case never reaches the default case.

I am making a game where you need to match up a falling ball to a matching color platform. I am using switch-case to detect which color is generated and which platform the ball hit.

void OnTriggerEnter2D (Collider2D col)
    {
        //if (col.gameObject.tag == "green" && color == 0)
        //{
        //    addScore();
        //}

        //if (col.gameObject.tag == "red" && color == 1)
        //{
        //    addScore();
        //}

        //if (col.gameObject.tag == "yellow" && color == 2)
        //{
        //    addScore();
        //}

        //if (col.gameObject.tag == "blue" && color == 3)
        //{
        //    addScore();
        //}
        //else
        //{
        //    Destroy(this.gameObject);
        //    Debug.Log(true);
        //}

        switch (col.gameObject.tag)
        {
            case "green":
                if (color == 0) { addScore(); }
                break;

            case "red":
                if (color == 1) { addScore(); }
                break;

            case "yellow":
                if (color == 2) { addScore(); }
                break;

            case "blue":
                if (color == 3) { addScore(); }
                break;
            default:
                Destroy(this.gameObject);
                Debug.Log("TRUE");
                break;
        }
    }

the if-else statements work just fine, but the switch-case “default” is never reached, it just skips over it. I looked at many examples of switch-case and I think I got the syntax right but it’s not working.

This happens because it will only go to the default state if the tag is not any of those four colors. Is there a tag like “pink” for instance? if the tag activated is “pink”, it will go to the default state.

In your if/else code, you want the tag to be blue AND the color to be 3. If those 2 conditions are not met, it will destroy the object. But in you switch code, you only need the tag to be met, That’s the difference.

for the switch to work it needs to be like this:

        switch (col.gameObject.tag)
        {
            case "green":
                if (color == 0) { addScore(); }
                else
                    Destroy(gameObject);
                break;

            case "red":
                if (color == 1) { addScore(); }
                else
                    Destroy(gameObject);
                break;

            case "yellow":
                if (color == 2) { addScore(); }
                else
                    Destroy(gameObject);
                break;

            case "blue":
                if (color == 3) { addScore(); }
                else
                    Destroy(gameObject);
                break;
            default:
                Destroy(this.gameObject);
                Debug.Log("TRUE");
                break;
        }