- Home /
 
Trying to display object name of raycast hit
Hey
All I'm trying to do is get the name of a raycast mouse over. But with this current code, I'm getting Null reference exceptions. Anything I'm doing that's wrong here?
 function Update ()
 {
      var hit : RaycastHit;                                                        
      var ray = Camera.main.ScreenPointToRay ( Input.mousePosition );    
 
      if (Physics.Raycast (ray, 30) && Input.GetMouseButtonDown(0)) 
     {
         print (hit.collider.gameObject.name);
     }
 }        
 
              Also for efficiency's sake you should put the raycast in the if InputGet$$anonymous$$ouseButtonDown check, not the other way around, unless you have some other reason to be checking every frame what the mouse is over.
Answer by ziv03 · Jan 04, 2014 at 12:40 AM
That's because you don't assign the raycast to the hit var. try this:
 function Update ()
 {
      var hit : RaycastHit;                                 
      var ray = Camera.main.ScreenPointToRay ( Input.mousePosition );    
      hit = Physics.Raycast (ray, 30);
      if (hit && Input.GetMouseButtonDown(0)) 
      {
        print (hit.collider.gameObject.name);
      }
 }  
 
              Your answer
 
             Follow this Question
Related Questions
Raycast from NPC 0 Answers
Cant jump while running left or right c#? 3 Answers
why gameobject / raycast when dragged is not accurately following the touch position in unity 0 Answers
raycasting throught the back of plane 2 Answers
shooting raycast 1 Answer