Sprite: SpriteRenderer.FlipX vs transform.localScale - when and why!

Hi everyone!

When working on flipping the sprite in this course I found 2 sollutions that seem to work in this case. I searched a bit online as to why use one over the other and I thought I’d share it here :slight_smile:

Option 1:

I have seen this option a few times and for me it looked more ‘usefull’ than to scale the object.
BUT! There is a reason why you should NOT do this!
When working with child sprites, they also get flipped which could result in weird outputs!
Read this post about this on the Unity forum for a good example:
https://forum.unity.com/threads/flip-x-or-scale-x.1042324/

Option 2
Ofcourse option 2 being the way that is shown in the course itself using scaling instead of actually flipping the sprite! In the link above is also explained why this is better in some cases

Here I just want to show a more ‘compact’ way of writing the code. For if anyone doesn’t like all those brackets all over the place :slight_smile:
NOTE: this way of writing if statements ONLY works if the code to be executed consists of only 1 line!
If you break up the code after the ‘if’ condition on multiple lines then only the FIRST line will run. In that case you DO need brackets to ‘group’ the code you want to have run when the condition evaluates to ‘true’

Hope this is of any use to anyone!

3 Likes

I might add that flipping the sprite might not always work if you are using other type of shader, so be careful with that.

Ben or Rick, in the previous version of the course, talked about that way of writing if statements and why they use brackets.

The idea of writing this…

if(whatever) { Do something; }

instead of

if(whatever) Do something;

Is that you don’t know if you’ll later add another line of code, it also makes the code a little bit clearer as to when the if statement ends.

I personally prefer using brackets for clarity’s sake, and I also have found myself having to add extra lines of code to one line if statements many, many times, so having the brackets already in place comes in handy.

Thanks for the addition to the Sprite flipping part. That is also a thing to consider then :slight_smile:

And yes, also true on the ‘if’ statement part. There are a couple of occasions where I always write it like I mentioned in my post and that is ofcourse when I think I won’t add another line of code later (not that I am always right thoug :stuck_out_tongue: )

An example of where I always leave the brackets is an early return as mentioned in the video as well:

if (!playerCapsuleCollider.IsTouchingLayers(LayerMask.GetMask("Ground"))) return;

The sole purpose of this is to return if false to prevent the player from jumping again. Big chance I won’t add to that statement in the future. In my initial post example I might add some code later yeah.

Privacy & Terms