Issues with Raycasting

Hi all.

I’m trying to prototype a basic interaction system in where the a first person camera looks at an object and presses a button to interact with it in some way. I followed a YouTube tutorial and ended up with the following Raycast script attached to my RigidBodyFPSController:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Raycast : MonoBehaviour
{
    private GameObject raycastedObj;

    [SerializeField] private int rayLength = 10;
    [SerializeField] private LayerMask layerMaskInteract;

    [SerializeField] private Image uiCrosshair;

    void Update()
    {
        RaycastHit hit;
        Vector3 fwd = transform.TransformDirection(Vector3.forward);

            if (Physics.Raycast(transform.position, fwd, out hit, rayLength, layerMaskInteract.value))
        {
            if(hit.collider.CompareTag("Object"))
            {
                raycastedObj = hit.collider.gameObject;
                CrosshairActive();

            if (Input.GetKeyDown("e"))
                {
                    Debug.Log("I HAVE INTERACTED WITH AN OBJECT!");
                    raycastedObj.SetActive(false);
                }
            }
        }
        else
        {
            CrosshairNormal();
        }
    }

    void CrosshairActive()
    {
        uiCrosshair.color = Color.red;
    }

    void CrosshairNormal()
    {
        uiCrosshair.color = Color.white;
    }

}

In Editor I have a Crosshair UI element which does not seem to be changing color when looking at a Cube which is set to the interact Layer and tagged ‘Object’. My RigidBodyFPSController’s Layer Mask element in the Raycast script component is set to Interact.

For what reason would the Crosshair not be changing color? Is the Raycast not working for some reason? And as pressing ‘e’ should write “I HAVE INTERACTED WITH AN OBJECT!” in the Debug Log, where can I find the Debug log to see if this has completed?

Thanks in advance.

Try removing layerMaskInteract.value.

Then, try removing hit.collider.CompareTag("Object")).

Finally, I don’t think Vector3 fwd = transform.TransformDirection(Vector3.forward); does what you think it does.

Don’t you mean to use a Camera raycast?

Perhaps I do mean to use a Camera Raycast, I was just following a YouTube video whilst loosely understanding the content. I mean to use a Raycast to detect interatcable Objects in the Player’s Crosshair. Are there any sources you could point me to that could explain how to do this better?