I'm playing with the System.Linq in unity and I wonder if this is possible to achieve:
I would like to search a list of RaycastHits and if it contains a hit with a specific component on it I would like to return it instead of the RaycasHit
hits.FirstOrDefault(hit => hit.transform.GetComponent<Target>());
This returns me a RaycastHit which contains the component Target. I would like to instead get that Target component immediately so I don't have to get component again in a new line
RaycastHit target = hits.FirstOrDefault(hit => hit.transform.GetComponent<Target>());
Target combatTarget = target.transform.GetComponent<Target>();
Is it possible to cast it or map it in one line ??
hit.transform.GetComponent<Target>()it givestarget,and not a condition, why you use it inside aFirstOrDefault. for me use justTarget combatTarget = hits.FirstOrDefault()?.transform?.GetComponent<Target>();GetComponenton the first entry inhits... which is not what you want ...