Sorting Sprite Order in Script

Aye, I’m trying to replicate player switch mechanic from sonic mania and have an issue with setting order in layer through script. This is what it currently looks like: 201372-test.gif

And here’s the code:

        private SpriteRenderer sprite;
        public bool playerSwitch = true;

        sprite = GetComponent<SpriteRenderer>();

        player1 = GameObject.FindGameObjectWithTag("Player");
        player2 = GameObject.FindGameObjectWithTag("Player 2");

The part above is above Start()

void CharacterSwitch()
    {
        
        if (Input.GetKeyDown(KeyCode.Q))
        {
            playerSwitch = !playerSwitch;

            if(this.gameObject == player1)
            {

                sprite.sortingOrder = 1;
                player2.GetComponent<SpriteRenderer>().sortingOrder = 0;
                
                //While this does change the sorting order, it does not revert them back yet because I haven't been able to figure it out.
            }
            else if (this.gameObject == player2)
            {
                //Reverts the thing above
                sprite.sortingOrder = 0;
                player2.GetComponent<SpriteRenderer>().sortingOrder = 1;
            }
        }
    }

This is what I have for the character switch mechanic but seems like the code does not change the values at all. I tried creating a second sprite renderer and doing the same thing but that somehow messed up the collision of the players.

EDIT: I fixed it by simply changing the if statements’ parentheses. I had to change the player1/player2 into playerSwitch/!playerSwitch.

I can’t seem to attach the gif itself but here’s the link to it: player switch gif

This is what I’m trying to do in my project as well.

Seems like the else if statement isn’t being called. I tried adding a debug.log but I can’t even see that message showing up.