Varied footsteps - Object reference not set to an instance of an object?

Hello!
My aim is to have different footstep sounds depending on the ground the player is walking on. The over all structure is this:
variable to determine if the player is walking, raycast down if player is walking to determine what ground he/she is on, play an audio clip depending on the tag.

I have this script so far, but I get the error “Object reference not set to an instance of an object?”… What is the problem here? I am not very experienced with raycasting unfortunately, haha.

var snow : AudioClip;
var metal : AudioClip;
var walking : boolean;

var hit : RaycastHit;
var rayHit : boolean;
 
function Update()
{
    var dwn = transform.TransformDirection (-Vector3.up);
      if(Input.GetKeyDown("w") || Input.GetKeyDown("a") || Input.GetKeyDown("s") || Input.GetKeyDown("d"))
        {
           walking = true;
        }

        else if (Input.GetKeyUp("w") || Input.GetKeyUp("a") || Input.GetKeyUp("s") || Input.GetKeyUp("d"))
        {
              walking = false;
        }		
	  
	  if (walking&&Physics.Raycast (transform.position, dwn)&&hit.transform.gameObject.tag == "metalfloor") 
        {
           audio.clip = metal;
           audio.Play();
        }		
		
		if (walking&&Physics.Raycast (transform.position, dwn)&&hit.transform.gameObject.tag == "snowfloor") 
        {
           audio.clip = snow;
           audio.Play();
        }		

}

Thanks for your time, you guys are great with questions :slight_smile:

So “hit” should be the problem. You declared “hit” but you didn’t use it when calling Physics.Raycast, so “hit” does not contain anything.

Try :

if (walking&&Physics.Raycast (transform.position, dwn, hit)&&hit.transform.gameObject.tag == "metalfloor")

Same for the “snowfloor” tag.

if (walking&&Physics.Raycast (transform.position, dwn)&&hit.transform.gameObject.tag == “metalfloor”)
{
audio.clip = metal;
audio.Play();
}

You haven’t used the variable hit as a parameter in Physics.Raycast(). I think this will fix your problem :

    if (walking && Physics.Raycast (transform.position, dwn, hit)) 
    {
        if(hit.transform.gameObject.tag = "metalfloor")
        {
            audio.clip = metal;
            audio.Play();
        }
    }

    if (walking && Physics.Raycast (transform.position, dwn, hit)) 
    {
        if(hit.transform.gameObject.tag = "snowfloor")
        {
            audio.clip = snow;
            audio.Play();
        }
    }