Quick solution for mouse clicks that don't hit

In MouseWorld add variable:
static Vector3 lastPosition = Vector3.zero;

and change GetPosition() to:

    public static Vector3 GetPosition()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Physics.Raycast(ray, out RaycastHit hit, float.MaxValue, instance.mousePlaneLayerMask);
        if (hit.collider != null)
        {
            lastPosition = hit.point;
        }
        return lastPosition;
    }

Now you will remain in place if your mouse click doesn’t hit the LayerMask.

That’s an interesting approach. Although it might lead to some confusion if in the future you have no collider hit and you forget that you implemented it in that specific manner and the function keeps returning the same value.
So if you’re afraid of invalid values I would simply refactor it to return bool, rename it to TryGetPosition(out Vector3 position);
That way it would be perfectly clear what the function was doing, if there was a mouse collision it would return the position, if not it would return false. With that approach it would eliminate any confusion in the future since it’s very clear what it’s doing.

3 Likes

Privacy & Terms