Search Unity

Raycast and SendMessage malfuction

Discussion in 'Scripting' started by Persona, Sep 21, 2011.

  1. Persona

    Persona

    Joined:
    Jul 25, 2010
    Posts:
    280
    I'm trying to cast a ray that sends a message to a script telling it to run damage functions.

    Code (csharp):
    1.  var hit : RaycastHit;
    2.  
    3.     var fwd = transform.TransformDirection(Vector3.forward);
    4.  
    5.    
    6.  
    7.     if (Physics.Raycast (rayReference.position, fwd, 100)) {
    8.  
    9.         print("There is something in front of the object!");
    10.  
    11.         Debug.DrawLine (transform.position, hit.point);
    12.  
    13.         hit.collider.gameObject.BroadcastMessage("Hurt4", damage4, SendMessageOptions.DontRequireReceiver);
    14.  
    15.         }
    16.  
    17. }

    Code (csharp):
    1. function Hurt4(damage4 : float){
    2. Health -= damage4;
    3. print("We're hit!");
    4. if(Health <= 0){
    5. Death();
    6. }
    7. }
    However, even when the ray registers a hit, the message doesn't get sent or work. I've tried attaching colliders and rigidbodies to ensure that it's hitting, but it just won't work. It constantly says: Object reference not set to an instance of an object

    Can anyone give me a reason or solution for this?
     
  2. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    your not filling the hit variable.

    take a look at the docs, you want the overload with the out RaycastHit and put your hit variable in there.

    edit: Physics.Raycast(rayReference.position, fwd, hit, 100)
     
  3. Persona

    Persona

    Joined:
    Jul 25, 2010
    Posts:
    280
    THANK YOU!

    Man, missing hours of sleep made me overlook that.
     
  4. bdev

    bdev

    Joined:
    Jan 4, 2011
    Posts:
    656
    yep :) just as a side note, if you avoid using RaycastHit as a member, you would have at least got a warning/error about using a uninitialized variable. Probably best to keep RaycastHit's as local variables when possible.