Checking the raycast

Hello,

I had my previous question closed for “Duplicate” reasons. When I wasn’t asking about “HOW TO MAKE A GUI APPEAR” I wanted help on how to recheck the raycast, as I keep getting errors when I tried adding the line: “if(Physics.Raycast(trasnform…)”

I have some code to check if the player is within a certain distance from an object (essentially a door) but want to add a GUI label popup to prompt the player when wanting to open the door. I’m not sure what I should use for the ‘if’ statement to check whether it’s within range. As you can see by the commented “if(RaycastHit Hit = true))”

    using UnityEngine;
    using System.Collections;
     
    public class New_Level_Door : MonoBehaviour {
     
    void Update()
    {
    if(Input.GetKeyDown(KeyCode.E) && CheckForDoor())
    {
    Application.LoadLevel("MainMenu");
    }
    }
     
    bool CheckForDoor()
    {
    RaycastHit hit;
    if(Physics.Raycast(transform.position, transform.forward, out hit, 2))
    {
    Debug.LogWarning("Press E to open the door");
    if(hit.transform.tag == "LevelEnd")
    {
    return true;
    }
    }
    return false;
    }
     
    void OnGUI()
    {
    //if(RaycastHit hit = true))
    {
    GUI.Label (new Rect(5,0,100,20 ),"Press 'E' to open the door!");
    }
    }
    }

Thanks for your time!

You have the general idea, you want to screen out non-door objects however.

Just have an if statement that checks if the raycast hit something (as you did above) and then compare the hit.transform.name or hit.transform.layer, or another property to uniquely identify that the hit object was a door.

You have the general idea.
Also, make sure to indent code, it helps in reading and debugging.
You can also do Debug.Log(“debug statement”); to output a string to the console to see if a particular code executes, and output variables, names, members, etc for debug purposes.

Also, separate code you’re unsure of into steps and make sure each step works before combining. Your code is simple enough to discern, but in complex scripts, it helps out a lot.

Happy scripting!