Search Unity

Could use reality check on the proper way to send messages to compound colliders

Discussion in 'Scripting' started by Steve-Tack, Mar 30, 2014.

  1. Steve-Tack

    Steve-Tack

    Joined:
    Mar 12, 2013
    Posts:
    1,240
    I'm curious if there's a typical way to handle a particular scenario. In my game, I have projectiles that need to hit space ships, some of which have single colliders at their root GameObject and some larger, more complex ships that have multiple colliders on some of their child GameObjects.

    The issue is with sending messages to them. I discovered that there's an "attachedRigidbody" property on Collider, which is a handy way to send an ApplyDamage message to the root GameObject where the script containing the ApplyDamage method lives. After some experimenting, I found that if the collider is at the root, it doesn't have that populated (which would have been nice).

    So I ended up doing this in my projectile class, and it worked for both types of ships:

    Code (csharp):
    1. public void OnTriggerEnter(Collider other)
    2.     {
    3.         // (left out data initialization)
    4.  
    5.         if (other.attachedRigidbody == null)
    6.         {
    7.             // Send message to object we collided with
    8.             other.gameObject.SendMessage("ApplyDamage", shieldCollisionData);
    9.         }
    10.         else
    11.         {
    12.             // Send message to the GameObject that has the rigidbody
    13.             other.attachedRigidbody.gameObject.SendMessage("ApplyDamage", shieldCollisionData);
    14.         }
    15.     }
    At first I tried other.gameObject.SendMessageUpwards() and that also worked, but I assume that's not ideal for performance.


    On a side note, what's interesting is that for beam weapons, I'm doing a Raycast, and from the RaycastHit it returns, I can do this and it appears to roll up to the parent automatically:

    Code (csharp):
    1. hitInfo.transform.gameObject.SendMessage("ApplyDamage", shieldCollisionData);
    I guess it's just how Raycast works. So those types of weapons worked in both scenarios right off the bat.



    So is there a "typical" way to deal with sending messages in this scenario in OnTriggerEnter? What I've got works, so that's good, but I'm curious how you guys deal with this, as it seems like it would be pretty common.