Script to flip a sprite over the x axis not working? C#, Unity2D

This script should work, right? Well, it doesn’t, I get no errors and my sprite is not flipping across the x axis, facing the other direction. Could somebody point out what I did wrong?

using UnityEngine;
using System.Collections;

public class LRmovement : MonoBehaviour {

public float speed = 1f;
public float JumpSpeed = 10f;
private bool onPlatform;

void Start () {

}

void Update () {
	if (Input.GetKey (KeyCode.D) && (transform.position.x < 1.5))
			transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
			transform.localScale = new Vector3 (-1f, 1f, 1f);

	if (Input.GetKey (KeyCode.A) && (transform.position.x > -1.5))
			transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
			transform.localScale = new Vector3 (1f, 1f, 1f);
}

}

Took me a few minutes to figure it out, but it’s actually pretty simple :smiley:

You use no braces (was: parenthesis) with your if statements: That is fine as long as you remember that in this case, only the next line will be affected by that if statement; All further lines are called as usual, which, in the case of Update(), is every frame. So what happens is that the localScale is set to 1,1,1 every frame, no matter which keys your are pressing or whatever conditions should apply. The fix is of course simple: Just encapsulate the relevant lines.

 if (Input.GetKey (KeyCode.D) && (transform.position.x < 1.5)) {//<- ding!
             transform.position += new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
             transform.localScale = new Vector3 (-1f, 1f, 1f);
  }//<- ding!
 
     if (Input.GetKey (KeyCode.A) && (transform.position.x > -1.5)) {//<- ding!
             transform.position -= new Vector3 (speed * Time.deltaTime, 0.0f, 0.0f);
             transform.localScale = new Vector3 (1f, 1f, 1f);
 }//<- ding!

Best of luck with your project.