As per title, in this chapter you explain the InteractWithCombat method, you cast a ray to see which targets are hit and then if you find any CombatTarget, you check the mouse to see if you have to perform anything and that’s all.
Then why not moving the
if (Input.GetMouseButton(0))
before all the rest of the method code? we need to execute something only if we click on a target, so checking first if the user clicked the mouse button, will save us from wasting CPU for nothing
Another observation is that, personally, I’d write the foreach without checking if null and then doing continue
but checking if different from null then attacking and then exiting the foreach with break
Basically my InteractWithCombat is
private void InteractWithCombat()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray);
foreach (var hit in hits)
{
CombatTarget target = hit.transform.GetComponent<CombatTarget>();
if (target != null)
{
fighter.Attack(target);
break;
}
}
}
}
P.S.
I’m saying this not to be fussy, but to emphasize to those who are reading and want to learn how to program well, that it’s not enough to write code “that works”, but you have to pay attention to the consequences of the code we write (especially in video games where the performance it is important and therefore avoiding running unnecessary code is to be kept in mind)
I know this code may be changed in next chapters, but every chapter should be self contained in terms of code or at least should be explained something like “we could have done things differently but we are changing the code in next chapters”