Why is my bool being set to true when program is run?
When I start the game I get the message "Functioning Properly" and I'm not sure why... Debug Windows is set to clear on play too.
using UnityEngine;
using System.Collections;
public class SimpleMovement : MonoBehaviour {
public bool movingBackwards;
public Vector2 thrustBackward;
public Vector2 thrustForward;
public Vector2 thrustUp;
public Rigidbody2D rb2D;
void Start ()
{
movingBackwards = false;
thrustBackward = new Vector2 (-10, 0);
thrustForward = new Vector2 (10, 0);
thrustUp = new Vector2(0,4);
rb2D = GetComponent<Rigidbody2D> ();
}
void Backward ()
{
rb2D.AddForce(thrustBackward, ForceMode2D.Force);
}
void Forward ()
{
rb2D.AddForce(thrustForward, ForceMode2D.Force);
}
void Jump ()
{
rb2D.AddForce(thrustUp, ForceMode2D.Impulse);
}
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
Forward();
if(Input.GetKeyDown(KeyCode.Space))
Jump();
if(Input.GetKey(KeyCode.LeftArrow))
Backward();
movingBackwards = true;
if (movingBackwards == true)
Debug.Log ("Functioning Properly");
}
}
Answer by TBruce · Oct 28, 2016 at 06:26 PM
It is because the variable movingBackwards
in the Update()
function is not within the if
block as intended which can be seen here
if(Input.GetKey(KeyCode.LeftArrow))
Backward();
movingBackwards = true;
In the above movingBackwards
is always set to true from the very first frame. You want to change the block to look like this
if(Input.GetKey(KeyCode.LeftArrow))
{
Backward();
movingBackwards = true;
}
Or you could move the variable movingBackwards
to the Backward()
function like this instead
void Backward ()
{
movingBackwards = true;
rb2D.AddForce(thrustBackward, ForceMode2D.Force);
}
But no matter what I would suggest either placing this
movingBackwards = false;
at the very top of the Update()
function or in in the Forward()
function. Otherwise once set to true the movingBackwards
variable will remain true.
Your answer
Follow this Question
Related Questions
My Bool function is returning False but it should be true in my opinion. Csharp C# 0 Answers
Why doesn't the collider work? 1 Answer
Movement with rigidbody 1 Answer
How can I get the player to face the direction it is going in a Unity 2D Game? 0 Answers
How to change the Bool for only a single prefab GameObject creating with Instantiate? 2 Answers