- Home /
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();
}
}
Answer by bunCBG · Aug 21, 2014 at 09:22 PM
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) ...
...
}
}
Answer by nsxdavid · Aug 21, 2014 at 08:43 PM
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.
Your answer
Follow this Question
Related Questions
OnTriggerEnter() parenting problem. 1 Answer
Ontriggerstay2d only runs 26 times in a row? 3 Answers
Is There A Way To Disable a Trigger But Still Use OnTriggerExit2D? (For COOP switch management) 2 Answers
OnTriggerEnter2D called twice sometimes when IsTrigger is ON 2 Answers
OnTriggerEnter2D not working 2 Answers