nullReferenceException within script, how?

I wrote a script that should make my player send a raycast and jump if the raycast collides with said objects, the jump works, but when i activate it I get a NullReferenceException, I tried to make an if statement if the rayhit is null but with little success. heres the script:

var jumpForce : float = 50.0;


function Update () {

var down = transform.TransformDirection(Vector3.down);
var hitJump : RaycastHit;


if(Input.GetButtonDown("Jump")){

		Physics.Raycast(transform.position, down, hitJump, 1.5);
		
			 if(hitJump.collider.gameObject.tag == "ground" || hitJump.collider.gameObject.tag == "jumpableObject" ){
			 
		
		
		rigidbody.AddRelativeForce(0,jumpForce,0);
		
		Debug.Log("grounded!");
		
		} else if(hitJump != null){
		
				
				
			Debug.Log(" Not Grounded!");
				
					}
				
				}

}

Thanks!

I tried your script and the error appeared when jump was hit and it did not come in contact with any collider. The reason you are getting that error is because when no collider is hit, the collider is null and therefore there is no tag to reference.

To fix this you can check if there was a collider that was hit before you check the tag:

var jumpForce : float = 50.0;
 
function Update () {
	var down = transform.TransformDirection(Vector3.down);
	var hitJump : RaycastHit;
	if(Input.GetButtonDown("Jump")){
		Physics.Raycast(transform.position, down, hitJump, 1.5);
		if(hitJump.collider != null){
			if(hitJump.collider.gameObject.tag == "ground" || hitJump.collider.gameObject.tag == "jumpableObject"){
				rigidbody.AddRelativeForce(0,jumpForce,0);
			}
		}
	}
}

It looked like you before you were checking to see if you hit anything or not, except you were checking if the hitJump itself was null rather than the collider and you were checking after you checked for the collider’s tag.

I hope this helped.