- Home /
Is there a way for an object to tell if it's being hit by a raycast?
As stated, there are many answers here that show how to get a raycast to return that it has hit an object. I was wondering if there was a way to do it backwards. Object says, yes I have been hit by a raycast, now I'm not.
Answer by Caeser_21 · 4 days ago
Maybe create a bool called IsBeingHit
in the respective object's script... Then use raycasts to just toggle it between true and false (By referencing the script with RaycastHit
)
Note : In Update()
add 2 if statements, one for when IsBeingHit
is true and one for when IsBeingHit
is false.
Answer by Llama_w_2Ls · 3 days ago
It would be better to create a function that you would use instead of raycast, which raycasts and also sends a message to any object it hits with a script. It could be like this:
bool Raycast(Ray ray, out RaycastHit hitInfo)
{
bool hit = Physics.Raycast(ray, hitInfo);
if (hit)
{
hit.collider.gameObject.SendMessage("OnRaycastHit", gameObject);
}
return hit;
}
And on any monobehaviours you would like to know that it was hit by a raycast, you add the method: void OnRaycastHit(GameObject hitter)
Your answer
Follow this Question
Related Questions
simple way to send a message threw a raycast 1 Answer
Why is my raycast returning true to a wall collision that isn't there? 1 Answer
How To Really Do High Quality Bullet Physics like in AAA Titles 1 Answer
Raycast results different on two devices 2 Answers
ray cast direction callabration? 0 Answers