-1

Simply put, every time round my update loop, a variable 'direction' begins as true, until I change it to false. But there is nothing that should change it to true.

Below in the code, you can see my Debug.Logs to check the value of it, when the if statement with the logs in is true, the first log always outputs true and the second outputs false. I'm not sure why it is being set to true between loops. Have I been stupid or is there a problem with how I'm doing it?

For more information, the variable is controlling the horizontal direction my gameobject will travel. While true, the object will travel in the positive x axis, and opposite for false.

private bool direction = true;
public int minX;
public int maxX;

public int changeScene;

// Use this for initialization
void Awake() {
    instance = this;
}

void Start () {
    reference = gameObject;
    StartCoroutine (WaitThenDestroy ());
}

// Update is called once per frame
void Update () {
    this.transform.Translate (new Vector3 (0, speed * movement.gameSpeed, 0));
    moveHorizontal();
}

private void moveHorizontal() {
    if (direction = true) {
        this.transform.Translate (new Vector3 (speed * movement.gameSpeed, 0, 0));
    } else {
        this.transform.Translate (new Vector3 (-speed * movement.gameSpeed, 0, 0));
    }

    // Change horizontal direction
    Vector3 p = this.transform.position;
    Debug.Log (p.x);
    if (p.x > maxX) {
        direction = true;
        Debug.Log ("WHOOP");
    } else if (p.x < minX) {
        Debug.Log (direction);
        direction = false;
        Debug.Log (direction);
    }
}
Mattattack
  • 179
  • 6
  • 21
  • Possible duplicate of [Why do assignment statements return a value?](https://stackoverflow.com/questions/3807192/why-do-assignment-statements-return-a-value) – mjwills Jan 15 '19 at 20:24

1 Answers1

3

You're assigning the value in an if statement:

if (direction = true)

Should be (edited to apply commenter's suggestion. Best practice is to check booleans without == operator)

if (direction)
Eliasar
  • 1,067
  • 1
  • 7
  • 18
  • Aha I knew I was being stupid somewhere ! Good spot! – Mattattack Jan 15 '19 at 20:24
  • 2
    Yeah, one of the problems of doing a direct comparison with a `bool` inside an `if` condition is that, because an assignment operation returns the assigned value, this error doesn't get caught (whereas you would get a compile time error if were checking a different type of object, like `string foo = "x"; if (foo = foo) {}`). A general practice would be to never check `== true` explicitly in an `if` condition, but rather just do: `if (direction)`. – Rufus L Jan 15 '19 at 20:38