Problems with Keys and Doors... (and Raycasting to)

I’m trying to have a animation play and open a door after a player picks up a key. The error I keep getting is on the 17th line and it says “Use of local unassigned variable “hit”” but I assigned hit earlier.

using UnityEngine;
using System.Collections;

public class Keys : MonoBehaviour {

    public bool Key;

    public bool hasKey;
   
    void  Update (){
        if(Input.GetKeyDown(KeyCode.E)){ //If E is pressed
            Debug.Log("Pressed");
            RaycastHit hit;
            Vector3 fwd = transform.TransformDirection(Vector3.forward);
            if (Physics.Raycast (transform.position, fwd, 5)) {// Sends out a raycast to check if something is in front of you 
                Debug.DrawRay(transform.position, fwd * 5, Color.green); 
                if(hit.transform.name.Equals("Key")){ // If the object in front of you has the tag Key
                    hasKey = true;
                    Destroy(hit.transform.root.gameObject);//Destroy Key Object
                    animation.Play("myAnimation");
                }else if(hit.transform.name.Equals("Door")){ //Checks if the gameobject you're looking at has the tag Door
                    if(hasKey)
                        Debug.Log("HasKey");
                    hit.transform.SendMessage("Unlock"); //Calls the function Unlock on the door
                }
            }
        }
    }
}

The problem is that while you have declared your “hit” variable on line 13, you never actually assigned anything to it later in the code.

Instead of Physics.Raycast (transform.position, fwd, 5) on line 15 (which doesn’t include RaycastHit info), try using Physics.Raycast (transform.position, fwd, out hit, 5) instead (which does).

Edit: Another thing… Line 17 should perhaps say hit.transform.name.Equals(“Key”) instead of transform.name.Equals(“Key”)? Just an observation.

Thanks, now the error is gone !