- Home /
How do I check if raycast is hitting a gameobject?
Hey I have a problem I need to show some text whenever a raycast hits a building. That's no problem, but if I etc. look up in the sky after looking at a building the text will still be visible. Here's the code:
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 25)) {
if(hit.collider.gameObject.layer == 8 && hit.collider != null) {
actionMenu = true;
return;
}
actionMenu = false;
}
}
So my question is... How do I check if my raycast is still hitting a gameobject and if not it should return false.
Answer by Zaeran · Nov 03, 2013 at 02:05 PM
Your 'actionMenu = false' is located inside your if (raycast) statement. This means that it will only return false if the second if statement fails.
You need to move your 'actionMenu = false' into an else statement after your 'If(raycast)' block.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121149im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
rayCastHit question 1 Answer
RaycastHit Collider Question 1 Answer
What are the hit coordinates from raycasting? 1 Answer
Vertical auto-aim with raycasts 1 Answer
Raycast always hit 1 Answer