Raycast going through objects

Hello Im making a game and I raycasts are going through walls.

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

public class GrannyEye : MonoBehaviour
{
    public GameObject granny;
    public float raycastDist;

    // Start is called before the first frame update
    void Start()
    {
     
    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hitInfo;
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        Debug.DrawRay(transform.position, fwd * raycastDist, Color.red);
        if (Physics.Raycast(transform.position, fwd, out hitInfo, raycastDist) && hitInfo.collider.gameObject.tag == "Player")
        {
            granny.GetComponent<EnemyAIGranny>().seePlayer = true;
        }
        else
        {
            granny.GetComponent<EnemyAIGranny>().seePlayer = false;
        }
    }
}

this is the code for it and when I shoot a raycast its going through objects like cubes and walls and doors, please help me fix that. in every script I write that contains raycasts, the raycasts are just going through objects. the objects have a collider, a mesh renderer, a mesh filter but raycasts are still going through them. please help me



Hi,

The visual line that you’re seeing is I believe drawn by this line of code :
Debug.DrawRay(transform.position, fwd * raycastDist, Color.red);
Here, the ray will always be at the same size, and will never stop at an object.

If you want to draw a ray that will stop at the first collider, you have to change the ray anytime the raycast is hitting something.

Like this :

if (Physics.Raycast(transform.position, fwd, out hitInfo, raycastDist) && hitInfo.collider.gameObject.tag == "Player"))
{
    Debug.DrawRay(transform.position, fwd * hitInfo.distance, Color.red);
    granny.GetComponent<EnemyAIGranny>().seePlayer = true;
}

With this code, ray will not be drawn if nothing’s hit. Up to you if you want to keep the current behaviour you’re having.

Hope this helps !

The problem is, with other rays raycasts are still going through walls, like when I wanna open a door, I shoot a raycast. but now I can open doors through walls