Raycast is not being detected. (Problem Solved!)

My ray casts are clearly being shot out when I go into the game but the problem is that it’s not detecting the items I’ve tagged as Key or Door when it casts them. the key doesn’t get destroyed and the door doesn’t open.

using UnityEngine;
using System.Collections;

public class Keys : MonoBehaviour {


    public float maxKey = 5;
    public float curKey = 0;

    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, out hit, 10)) {// Sends out a raycast to check if something is in front of you
                Debug.DrawRay(transform.position, fwd * 10, Color.green);
                if(hit.transform.Equals("key")){ // If the object in front of you has the tag Key
                    Debug.Log("the Key Is There");
                    curKey += 1;
                    Destroy(hit.transform.root.gameObject);//Destroy Key Object
                    animation.Play("Door");
                }else if(hit.transform.name.Equals("Door")){ //Checks if the gameobject you're looking at has the tag Door
                    if (curKey == 1)
                        Debug.Log("HasKey");
                    animation.Play ("New Animation"); //Calls the function Unlock on the door
                    curKey -=1;
                }
            }
        }
    }
}

I think you should then check for hit.CompareTag(“Key”) or such…

and is your tag “Key” or “key” ?

I’ve switched the tag around to try and get it to work, so I’ve tried both Key and key. I’ll check this new thing out thanks.

Instead of:
if(hit.transform.Equals(“key”))

Try:
if (hit.transform.gameObject.tag == “Key”)

That worked super well thanks.

1 Like

Okay so now the key is picked up and added to the value but the animation for the door opening does not play. Do I need to create a new script that calls to this one to open the door or is there still something wrong with this one. I changed (hit.transform.name.Equals("Door")
to
}else if(hit.transform.gameObject.tag == "Door"){.

1 Like

Are you sure the name of the animation is New Animation? animation.Play(“New Animation”);

Yes, it was called “door” at first but I changed it to “New Animation” for the sake of testing the script.

You are calling animation.Play(“New Animation”);
Shouldn’t you be calling something like "hit.transform.gameObject.animation.Play(“New Animation”); ?

The doors now work. thanks for your help.

1 Like