There is actually a tiny difference in the code, which you have correct in the comments, but not in the active version.
The warning is coming because within the if block, you never actually use the RaycastHit. It’s suggesting that rather than allocate a variable here, you simply use out _
for the parameter. This construction is used whenever you’re calling a function or subscribing to an event handler that you don’t care about a particular parameter.
In this case, for Physics.Raycast, you must have an out parameter, but that doesn’t mean you don’t have to use it.
Replacing the RaycastHit parameter with _, however would be a mistake in this instance.
You next test the selectedUnit.transform.TryGetComponent instead of the RaycastHit, which will mean that no matter what unit you click on, only the selectedUnit will be returned.
Here’s the correct code, which calls the raycastHit.transform.TryGetComponent method.
private bool TryHandleUnitSelection()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, unitLayerMask))
{
if (raycastHit.transform.TryGetComponent<Unit>(out Unit unit)) //<<note using raycastHit not selectedUnit here.
{
selectedUnit = unit;
return true;
}
}
return false;
}