How can i make the ray cast don't go through the walls

So basically i want to know what shell i add to this code so the raycast wont go through the GameObjects here’s the code.

var Range : float;

function Update () {

var forward = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;

Debug.DrawRay(transform.position , forward * Range ,;

if (Input.GetMouseButtonDown(0)){
if (Physics.Raycast(transform.position , forward , hit , Range)){

if ( == "Cube1"){


Raycast() stops a the first collider it finds. You need multiple layers and layer masks to get Raycasts to ignore an object. Given that you are not using a mask in your Raycast(), the problem is elsewhere. I see two possibilities.

One line 17, you use gameObject.Find(“Cube1”). This will find a game object with that name, but, unless there is exactly one object with that name in the scene, it will not necessarily find the game object hit by the collider. You can change your code to:


The other possibility concerns how your walls are constructed. If you made them out of planes and used a shader with culling turned off, then you will have a problem. Planes are one-sided, so they will only report a hit from one side. If this is the problem you can change the collider on your walls to a Box colliders.