Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Scripting' started by RiseBestgirl, Jan 8, 2015.

  1. RiseBestgirl

    RiseBestgirl

    Joined:
    Dec 17, 2014
    Posts:
    10
    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.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Keys : MonoBehaviour {
    6.  
    7.     public bool Key;
    8.  
    9.     public bool hasKey;
    10.    
    11.     void  Update (){
    12.         if(Input.GetKeyDown(KeyCode.E)){ //If E is pressed
    13.             Debug.Log("Pressed");
    14.             RaycastHit hit;
    15.             Vector3 fwd = transform.TransformDirection(Vector3.forward);
    16.             if (Physics.Raycast (transform.position, fwd, 5)) {// Sends out a raycast to check if something is in front of you
    17.                 Debug.DrawRay(transform.position, fwd * 5, Color.green);
    18.                 if(hit.transform.name.Equals("Key")){ // If the object in front of you has the tag Key
    19.                     hasKey = true;
    20.                     Destroy(hit.transform.root.gameObject);//Destroy Key Object
    21.                     animation.Play("myAnimation");
    22.                 }else if(hit.transform.name.Equals("Door")){ //Checks if the gameobject you're looking at has the tag Door
    23.                     if(hasKey)
    24.                         Debug.Log("HasKey");
    25.                     hit.transform.SendMessage("Unlock"); //Calls the function Unlock on the door
    26.                 }
    27.             }
    28.         }
    29.     }
    30. }
    31.  
     
    Last edited: Jan 8, 2015
  2. Xoduz

    Xoduz

    Joined:
    Apr 6, 2013
    Posts:
    135
    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.
     
  3. RiseBestgirl

    RiseBestgirl

    Joined:
    Dec 17, 2014
    Posts:
    10

    Thanks, now the error is gone !