Why does changing the scale of my object break its child's shader?

Viewed 503

I have a player game object. Whenever I change direction, I flip the player's x scale, so it's 1 when he's facing right and -1 when he's facing left.

This code is responsible for flipping the player scale and moving the player horizontally:

void FlipScale()
{
    facingRight = !facingRight;
    transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y);
}

void MoveHorizontally()
{
    if (wantsToMoveLeft && wantsToMoveRight) { return; }

    if (wantsToMoveRight)
    {
        rb.velocity = new Vector2(runVelocity, rb.velocity.y);
        if (!facingRight) { FlipScale(); }
    }
    else if (wantsToMoveLeft)
    {
        rb.velocity = new Vector2(-runVelocity, rb.velocity.y);
        if (facingRight) { FlipScale(); }
    }
}

The player object has a child object, which has the main sprite renderer that uses this shader material:

Dissolve Material

Continuously changing the Fade from 1 to 0 creates an effect of the player dissolving, finally disappearing completely at 0. Here is what it looks like half-way:

Player Dissolving

However, when I flip the player using the script above, the shader breaks, and the player disappears. Additionally, when I change the Fade value from 1 to exactly less than 0.1, the player suddenly appears to be glowing:

Player Glowing

Flipping the sprite again does not fix the issue. Furthermore, flipping the sprite through the inspector does not break the shader, only when I do it through code. I used this tutorial to create this shader: https://www.youtube.com/watch?v=WiDVoj5VQ4c. This is my current shader graph:

Dissolve Shader Graph

I have just started using shaders, so I apologise if the problem is very obvious. I tried a lot of fixes on stack overflow and other websites, but nothing has worked so far. If I didn't include enough information, please ask.

EDIT 1: Found out that, when the shader breaks, the player starts glowing whenever the Fade value is below the Edge value. If it's the same or above, the player looks normal, but the dissolve effect still doesn't work.

EDIT 2: Changing to an unlit shader doesn't fix the issue.

1 Answers

So I recently came back to the project and after testing for about an hour, I facepalmed myself really hard when I found out the problem.

I was using Vector2 to flip the scale!!! Vector2 defaults the z value to 0. That's why flipping it in the inspector didn't break anything...

The solution is to simply use Vector3 like so:

transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, tranform.localScale.z);

or:

transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, 1f);
Related