Getting object hit by RayCast

Is there a better way to call some methods on objects given by hit?
I wish I didn’t have to know GetComponent
like:
var target = hitInfo.transform.GetComponent();

RaycastHit2D hitInfo = Physics2D.Raycast(firePoint.position, firePoint.right);


if (hitInfo)
{
   
    Enemy enemy = hitInfo.transform.GetComponent<Enemy>();
    Player player = hitInfo.transform.GetComponent<Player>();

    if (enemy != null)
    {
        enemy.TakeDamage(damage);
    }
   
    if (player != null)
    {
        player.TakeDamage(damage);
    }

One way to clean it up is to have interfaces. You still use GetComponent<>() but you could produce a common interface such as “IDamageTaker” and then anyone who CAN take damage from this shot would be notified. You could have 57 different player types and 57 different enemy types and this code would not change, as long as all those player types and enemy types implemented the IDamageTaker interface.

Here’s a blurb I wrote up in the forums here: Using Interfaces in Unity3D:

The above example is in lieu of SendMessage but it applies equally well to your use case with Raycast. There are plenty of other tutorials about doing it too. It lets you clean up your code nicely conceptually, because any object can implement as many interfaces as it wants.

1 Like

Make an interface:

public interface CanTakeDamage {
  void TakeDamage(float damage);
}

Then have Player and Enemy both implement the interface:

public class Player : MonoBehaviour, CanTakeTamage {
  public void TakeDamage(float damage) {
    myHealth -= damage;
  }
}

Then in your raycast code:

if (hitInfo)
{
 
    CanTakeDamage damageable = hitInfo.transform.GetComponent<CanTakeDamage>();
    if (damageable != null)
    {
        damageable.TakeDamage(damage);
    }
1 Like