Faster way to check if object has component?

Good evening.

I’m making a game where explosions are a thing. In this game there are a lot of different types of objects that can be damaged. Glass, characters, vehicles, and all of them receive different inputs for their Damage() method, so making a generic base class that they can inherit from is a no-go. The way I currently have it set up to check what type of object it is is in a manner similar to the following:

Glass g = col.GetComponent<Glass>();
if (g)
{
    //Do glass stuff
}
else
{
    CharacterLimb c = col.GetComponent<CharacterLimb>();
    if (c)
    {
        //Do character stuff
    }
    else
    {
        //And so on and so forth
    }
}

This… works. But it has a huge toll on performance in the case of bigger explosions that have a radius of 50 metres or larger, since it has to go through a lot more colliders (defined as c in the above code) and do all of that for each one.

Is there a better way to do this? Short of making a “data” component that has a variable for caching every type of damageable component… which I could do, but would rather get a second opinion first.

I wouldn’t go this way. Instead, define an interface defining a single function you will be able to call from your collision method:

public interface Foo
{
    void Bar();
}

public class Glass : Foo
{
    public void Bar()
    {
         Debug.Log("Glass");
    }

}

public class CharacterLimb : Foo
{
    public void Bar()
    {
         Debug.Log("CharacterLimb");
    }

}

Then:

 if(col.TryGetComponent(out Foo foo))
     foo.Bar();