- Home /
 
Raycast retuning info of hit object
Hi guys, I believe this is a very simplistic question, but I havent managed to find an answer to this one (at least one that I would understand).
My code:
   bool bIsButtonDown = Input.GetButton("Fire1");
             if (bIsButtonDown)
             {
                 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                 RaycastHit rch;// = new RaycastHit();
                 
             }
 
               After hitting an object I would like to get info (tag, or more prefferably name) of the object. My goal is very simple - three boxes in the scene, and I want something to happen when one of them is hit. After getting info it is probably just a simple "switch" but I can`t seem to understand how to get that info.
Being a noob, it will help me even if you can at least point me in the right direction. :)
Answer by farooqaaa · Mar 24, 2012 at 03:38 PM
To do a raycast you can use Physics.Raycast() method:
 bool bIsButtonDown = Input.GetButton("Fire1");
 if (bIsButtonDown)
 {
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     RaycastHit rch;
     if(Physics.Raycast(ray, out rch))
     {
        // do something
        // rch variable contains all the info about the object that is hit
     }
 }
 
              Thank you! I didn`t know that, now it works like a charm! :) In case anyone else needs the same thing I just used this line:
name = rch.collider.name; Debug.Log(name);
Is there a way of only doing something if the raycast hits a specific object? If so, how do you confirm that the object was hit by the ray:
 if(Physics.Raycast(ray, out rch))
 {
     if(*ray hits specific object*)
     {
         // do something
     }
 }
 
                  I know this question was asked two years ago and that this is a long shot but hey! :P
@Gerflukon lol almost exactly a year later :P Use RaycastHit.transform.gameObject, as per this page:
http://answers.unity3d.com/questions/141529/getting-gameobject-from-raycast-hit.html
Your answer
 
             Follow this Question
Related Questions
how to get info on what raycast hitted 1 Answer
I don't know why i can't detect by ray sth. tagged, 1 Answer
Raycast on mini-map 0 Answers
Exclude tag from raycast 1 Answer
Click&Drag Misterious Disappearing! 1 Answer