Search code examples
unity-game-enginespritescaleflip

Weird behavior from local scale flip


I'm currently working on a 2D game with sprites and stuff like that.

When I tried to flip a sprite via code I found something really strange, here's the code:

Vector3 theScale = transform.localScale;
theScale.x = isMovingLeft ? 1 : -1;
transform.localScale = theScale;

// Same code but in one line
//transform.localScale = Vector3.right * (isMovingLeft ? 1 : -1);

Basically, when the sprite reaches the end of the waypoints list, it just flips to the opposite direction.

But if I use the one line commented in the code above the sprite just disappears (but continue to flip normally in the inspector), and if I use the three lines of code (with a local variable) the sprite works perfectly.

Can someone know why this is happening? Is it a bug or a reference/value thing?

Thanks :)


Solution

  • Vector3.right will be 0,0,1. So only one dimension will actually have a size (as the rest gets multiplied with 0). It kind of gets "squished" to nothing.

    In your current uncommented code you actually use the localScale. I assume that .y and .z property will be non zero. Therefore you will still see it, when you invert the .x property.