Greetings all! First off, I’m absolutely loving this course, so kudos and abundant thanks to the lovely folks at GameDev. My question might be a bit pedantic, but I’d love to hear the communities’ thoughts, so here goes: In the InteractWithCombat function, I noticed that Sam ran the foreach loop then checked for Input.OnMouseButtonDown, and I got this working without any issue… but I also reversed the order, checked for the mouse button press first, then grabbed the RaycastHit array (Why am I picturing Rick saying those two words over and over as a tongue twister while chuckling?), and ran the foreach loop, and this also works. So… my question regards performance and optimal operational order. Would there be any real difference between the two cases? Short of running tests with 100k iterations, I’m more than content to get opinions from more experienced coders. I realize that a foreach that goes through only a couple objects every frame would probably have no noticeable impact, but my brain is wired for code efficiency, and checking for the mouse click at the beginning makes more sense to me. Please be brutal. I can take it… or I have a supply of tissues handy for worst case!
The altered order for the InteractWithCombat function:
void InteractWithCombat() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit[] hits = Physics.RaycastAll(GetMouseRay());
foreach (RaycastHit hit in hits) {
CombatTarget target = hit.transform.GetComponent<CombatTarget>();
if (target == null) { continue; }
GetComponent<Fighter>().Attack(target);
}
}
}