So I made a function, to use OverlapSphere, and get all nearby objects(classes) within a set radius:
public List<Hex> RadiusSearchForHex(Hex hex, float radius)
{
List<Hex> list = new List<Hex>();
foreach (var collider in Physics.OverlapSphere(hex.worldPos, radius))
{
if (collider.transform.parent.TryGetComponent<Hex>(out Hex nearby))
{
if (nearby != hex && nearby.myType == Hex.TypeOfHex.Land)list.Add(nearby);
}
}
return list;
}
And I was happy with it, yet Visual Studio did it’s common “this can be improved” suggestion, so for the giggles of it I let it try to simplify it:
public List<Hex> RadiusSearchForHex2(Hex hex, float radius)
{
return (Physics.OverlapSphere(hex.worldPos, radius).
Where(collider => collider.transform.parent.TryGetComponent<Hex>(out Hex nearby)).
Where(collider => nearby != hex &&
nearby.myType == Hex.TypeOfHex.Land).Select(collider => nearby)).ToList();
}
It gives errors on each “nearby” on second “Where”, and I tried playing around with fixing it, but it seems the “Where” methods only wish to use the “collider” reference, and cannot see that “nearby” was declared. Which to my own conclusion, I would have to GetComponent from the collider several times, in order to keep the suggested code.
I will admit, the lamda(=>) operator still throws me for a loop sometimes, but I think it’s more the “Where” in this situation since it seems purely focused on the returned colliders, and doesn’t register “nearby”.
I’ve pretty much given up on this, and plan to stick to my original method. But for the giggles of it, is anyone able to say for sure that the suggested code would never work the way I intend it to?(if there’s no real performance gain, especially)
