How to GetComponent once for multiple comparisions

I feel like there is a better way to do this. Right now in each if condition I have to get the trigger, the gameobject, and ask for its component. I’m looking for a way to just get the component once, and ask if it equals this or this… It just seems inefficient to have to keep using GetComponent. As a programmer, when I see I have to do something over and over, it’s a heads up that something could be better.

Any ideas?

For example:

void OnTriggerEnter2D(Collider2D trigger){
   var triggerHit = trigger.gameObject.GetComponent<T>();

   if(triggerHit == LedgeTrigger){
     ...
   }
   ...
}



// Actual Code
     void OnTriggerEnter2D(Collider2D trigger){
            		if(trigger.gameObject.GetComponent<LedgeTrigger>() != null)
            			HitLedge();
            		else if(trigger.gameObject.GetComponent<WallTrigger>() != null){
            			HitWall();
            		}
            		else if(trigger.gameObject.GetComponent<Door>() != null){
            			HitDoor();
            		}
            	}

You can achieve something similar if all of your trigger classes are in the same hierarchy.

For example:

abstract public class AbstractTrigger : MonoBehavior { ... }

public class LedgeTrigger : AbstractTrigger { ... }

public class WallTrigger : AbstractTrigger { ... }

Then you can do this in OnTriggerEnter2D:

void OnTriggerEnter2D(Collider2D trigger) {
    AbstractTrigger t = trigger.gameObject.GetComponent<AbstractTrigger>();

    if (t != null) {
        if (t is LedgeTrigger) ...
        if (t is WallTrigger) ...
        ...
    }
}

Easy, you cache it yourself:

Create a variable on your class to hold a reference to the component and do the GetComponent<> once in your start method and use that variable everywhere else in your class.