I’m trying to make a piece of code which will make a object randomly go left or right. I have a Boolean called “goingLeft”. Which should determine if the object should move left or not. But the boolean never changes…! I have no Idea what I am doing wrong, could someone take a look at my code?
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float speed = 10;
public bool goingleft = false;
void Start () {
walkChoice();
}
void Update()
{
if (goingleft = true)
{
Debug.Log("going left as always");
transform.localScale = new Vector3(1, 1, 1);
transform.Translate(-Vector2.right * speed * Time.deltaTime);
}
else
{
Debug.Log("I should be going right");
transform.localScale = new Vector3(-1, 1, 1);
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
}
void walkChoice()
{
int chance = Random.Range(0, 2);
Debug.Log(chance);
if (chance < .5f)
{
goingleft = true;
Debug.Log("WalkingLeftNow");
StartCoroutine(wait());
}
else
{
goingleft = false;
Debug.Log("WalkingRightNow");
StartCoroutine(wait());
}
}
IEnumerator wait()
{
int waiting = Random.Range(1, 5);
yield return new WaitForSeconds(waiting);
Debug.Log("I am done waiting");
walkChoice();
}
}
So when the game starts, walkChoice gets called, which should determine if goingLeft is true or false. The choice gets made, in the debug I can see that both get pick randomly, but the boolean never changes…