Raycast going haywire!!

Hi Guys
So I am trying to get a raycast to stop at the first obstacle and not hit the objects next in line but so far no luck
I thought raycast was supposed to stop at first contact? but maybe I am doing something wrong.Anyway I put them both on the same mask layer.first is a large wall and the second is a sphere behind it.The ray keeps passing through the wall and hitting the sphere how can I prevent that?.
Thanks

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

public class Test raycast : MonoBehaviour
{ public GameObject first;
public GameObject second;

void Update()
{LayerMask mask = LayerMask.GetMask(“cull”);

RaycastHit hit;
if (Physics.Raycast (transform.position, first.transform.position-transform.position, out hit,mask))
{ Renderer rend=first.GetComponent();
Debug.DrawLine(transform.position,first.transform.position * 333333, Color.yellow);

if (Physics.Raycast (transform.position,transform.forward, out hit,mask))

{ Renderer rend2=second.GetComponent();
Debug.DrawLine(transform.position,transform.forward * 333333, Color.yellow);

rend.enabled=true;
rend2.enabled=false;
}
}}}

You probably want to use something like Debug.DrawLine(transform.position, hit.point, Color.yellow);

Also I think you are shooting two Rays. Seems much like this question: Stopping a raycast after hit - Questions & Answers - Unity Discussions

Bah I see what I did wrong.Just had to change the
rend2=second.GetComponent(); to
rend2.hit.collider.GetComponent();
The Debug.DrawLine(transform.position, hit.point, Color.yellow); got me where I needed to go.
Thx guys

2 Likes

Fun fact: the very first Raycast is still traveling today, right now passing at light speed through the neighborhood of Alpha Centauri.

Unfortunately it will never catch up the first forum post to fail to use code tags, which was several years prior to that first raycast.

If you post a code snippet, please, for all the little raycasts out there, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

2 Likes

I did try use the code tags except I was sleep deprived and used the quote insert instead:face_with_spiral_eyes:

1 Like