How can I get an object reference from a Raycast?
So I want to deactivate some houses I have in my level when the player goes behind them, by using a raycast. I shoot the raycast from the camera onto the player and check for things in between but I don't know how I can get the object reference so I'm able to deactivate the houses. Please help me. Thank you :)
Answer by Xarbrough · Dec 29, 2015 at 07:28 PM
Vector3 start = Vector3.zero;
Vector3 direction = Vector3.forward;
RaycastHit hit;
if(Physics.Raycast(start, direction, out hit))
{
hit.collider.gameObject.SetActive(false);
}
Physics Raycast gives you a reference to the collider, which was hit. It is stored in the out parameter as a RaycastHit. You can get information about the hit itself, the collider, transform, gameobject and so on from that hit variable.
Oh my god, i was using "hit.collider.gameObject" but it didn't work so I thought it was wrong, but I was doing "SetActive = false" ins$$anonymous$$d of "SetActive (false)". Thank you so much :D
Your answer
Follow this Question
Related Questions
Survival shooter enemy not taking damage 0 Answers
How to make an object move to the direction in which the user faces using vr gaze interaction? 1 Answer
Looking for an efficient way to use Raycast for many objects in a scene 0 Answers
Addressables' references - right object is there, but not! 1 Answer
How to freeze an GameObject on x axis in specific direction? 1 Answer