Boolean not going 'back' to false

Hey guys, I have this script for movement, and before you comment on the functionallity, you should know
that this script performs the kind of movement that I actually need it to.

My problem is, that I’m casting a ray form the player, and when it hits a wall, a boolean goes ‘true’. However, when the user is then looking away from the wall, that boolean should go back to false, and it doesn’t.
Can anybody tell me what the problem is, and how to fix it?

This is the script:
(the problem is in the *Raycast’ section of the script)

/* 
	
Movement Script for strict movement, 

1 unit at a time

*/

// Variables

public var playerCharacter : GameObject;

public var distance : float = 2;

private var playerZ = playerCharacter.transform.position.z;

var lookingAtWall : boolean = false;



// Move functions


// Forward movement

function moveForward()

{

	playerCharacter.transform.Translate(0, 0, 1);		

}


// Backwards movement

function moveBackwards()

{

	playerCharacter.transform.Translate(0, 0, -1);

}


// Rotate left

function rotateLeft()

{

	playerCharacter.transform.Rotate(0, -90, 0);

}


//Rotate right

function rotateRight()

{

	playerCharacter.transform.Rotate(0, 90, 0);

}


// Update function (runs once every frame)


function Update()

{


	/* RAYCAST */

	var dir = transform.forward;

	
	var hit : RaycastHit;
	

	Debug.DrawRay(transform.position, dir * distance, Color.blue);


	if( Physics.Raycast( transform.position, dir, hit, distance ) ){
	

		if( hit.collider.gameObject.tag == "Wall" ){
	

			print("You are looking at a wall!");

			lookingAtWall = true;
		

		}
		

		else if( hit.collider == "None" ){

			lookingAtWall = false;

		}
	

	}


	// If player presses 'W' and z-position is less than 8; move forward

	if(Input.GetKeyDown(KeyCode.W)  playerCharacter.transform.position.z <= 8  lookingAtWall == false){

	
		moveForward();

	
	}
	

	// If player presses 'S' and z-position is more than 1; move backwards

	if(Input.GetKeyDown(KeyCode.S)  playerCharacter.transform.position.z > 1){

	
		moveBackwards();
	

	}
	

	// If player presses 'A'; rotate left

	if(Input.GetKeyDown(KeyCode.A)){

	
		rotateLeft();
	

	}


	// If player presses 'D'; rotate right

	if(Input.GetKeyDown(KeyCode.D)){

	
		rotateRight();
	

	}


}

You are executing the reset of the boolean value within the raycasting if-statement. That means in case you don’t hit anything the script is never going to reach the part where the reset is supposed to happen. Simple solution: Set the bool to false even before you are doing the raycast:

lookingAtWall = false;	// <-- RESET

if( Physics.Raycast( transform.position, dir, hit, distance ) ) {
	if( hit.collider.gameObject.tag == "Wall" ) {
		print("You are looking at a wall!");
		lookingAtWall = true;
	}
}

That worked. :wink:
Thank you so much for your help. :slight_smile: