Out RaycastHit raycastHit is grey out when I enter it


I’m using 2022.3.20f1

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, unitLayerMask)) {          
  if (selectedUnit.transform.TryGetComponent<Unit>(out Unit unit)) {
        selectedUnit = unit;
        return true;
    }
}
return false;

Out RaycastHit raycastHit is grey out.

I’m not sure how to solve this and I followed the video exactly.

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;
    }

1 Like

Thanks Brian for your explanation. :slight_smile:
It is working now.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms