- Home /
How to detect raycast exiting
I have this script that detects when a raycast hits an object and runs a function from that gameObject.
How can I detect when the raycast leaves the object so I can run a different function to that gameObject?
using UnityEngine;
using System.Collections;
public class CastRays : MonoBehaviour {
SetRenderQueue srq;
void FixedUpdate()
{
RaycastHit hit;
Vector3 forward = transform.TransformDirection (Vector3.forward) * 7;
if (Physics.Raycast (transform.position, forward, out hit) && hit.transform.tag == "Block") {
print ("There is something in front of the object!");
srq = hit.transform.gameObject.GetComponent<SetRenderQueue> ();
srq.MakeTransparent (); //Run Function
}
Debug.DrawRay(transform.position, forward, Color.green);
}
}
As far as I know, Raycasts don't "exit" objects. They are cast in a direction and return whether they hit something and information about that object, but that is as far as they go.
Answer by Adamcbrz · Feb 08, 2018 at 08:53 PM
It looks like you are holding a reference to the last SetRenderQueue. So you know what the previous object was so before setting that variable again compare it and if it is different call another method before setting it to the new version.
....
print("There is something in front of the object!");
SetRenderQueue tempSrq = hit.transform.gameObject.GetComponent<SetRenderQueue>();
if(tempSrq != srq) {
srq.MakeOpaque();
srq = tempSrq;
}
srq.MakeTransparent(); //Run Function
Your answer
![](https://koobas.hobune.stream/wayback/20220612152229im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Fall collision force with help of raycast 0 Answers
RaycastHit.distance 1 Answer
Raycasting to detect which side of collider is hit 2 Answers
instantiate decal at raycastHit 1 Answer
Exclude tag from raycast 1 Answer