- Home /
 
              This question was 
             closed Sep 24, 2013 at 11:10 PM by 
             clunk47 for the following reason: 
             
 
            OP decided to go with different approach, issue resolved.
 
               Question by 
               ardizzle · Sep 23, 2013 at 09:54 PM · 
                raycasthitdetectionridgidbody  
              
 
              Why is this giving me a null refrence exeption?
I have a ray that shoots out of this collider and when it hits its suppose to detect that it hit an AI but not the player. So I tried this code:
 if(hit.rigidbody.tag == "AI")
 
               But it keeps giving me a null refrence exeption. But if I try it like this:
 if(hit.rigidbody == True)
 
               It hits the AI and the player. Why is it not finding the tag? Is there a better way to go about this?
Edit:
This is the code thats on the collider
 #pragma strict
 var carWaiting   : boolean = false;
 private var stop : String  = "Intersection";
 private var go   : String  = "Go";
 function Start ()
 {
     // This makes sure the colliders tag starts out as stop
     gameObject.tag = stop;
 }
 
 function Update () 
 {
     var back = transform.TransformDirection (Vector3.back);
      var hit : RaycastHit;
         
     if(Physics.Raycast(transform.position, back, hit, 100))
     {
      // The ray detects it hits something here
         if(hit.collider.gameObject.tag == "AI")
         {
                    //but doesn't detect the AI here
             print("I see a computer car");
             carWaiting = true;
         }
     }
 }
 
              
               Comment
              
 
               
              Change
hit.rigidbody.tag
to
hit.collider.gameObject.tag
Also, you can just use if(hit.rigidbody) to check if is true, or if(!hit.rigidbody) to check if something is false, hence the '!' meaning if(not), or if(something is false)
 if(hit.rigidbody)
 {
     if(hit.collider.gameObject.tag == "AI")
     {
         //DoSomething
     }
 }