RaycastHit hit returns null in Physics.Raycast

I’m creating a twin-stick mobile game and I’ve came to the point, where I need to implement weapon shooting mechanics.
I have AimComponent class, which is attached to weapon prefab. This class has method GetAimTarget, which returns object, that my gun is currently pointing.

[SerializeField] private Transform _weaponMuzzle;
[SerializeField] public float _aimRange = 1000;
[SerializeField] private LayerMask _aimMask;

        public GameObject GetAimTarget()
        {
            Vector3 aimStart = _weaponMuzzle.position;
          
            if (Physics.Raycast(aimStart, GetAimDirection(), out RaycastHit hit, _aimRange, _aimMask))
            {
                return hit.collider.gameObject;
            }
            return null;
        }
private Vector3 GetAimDirection()
{
    Vector3 muzzleDirection = _weaponMuzzle.forward;
    return new Vector3(muzzleDirection.x, 0f, muzzleDirection.z).normalized;
}

The problem is that RaycastHit hit always returns null, wherever I shoot.
_aimMask variable is set to Everything in editor. _weaponMuzzle is a transform of child object of Rifle prefab (Screenshot_1). It’s not colliding with weapon collider simply beacause weapon prefab has no collider. I’ve tried to debug ray with OnDrawGizmos method:

private void OnDrawGizmos()
{
       Debug.DrawRay(_weaponMuzzle.position,  _weaponMuzzle.position + GetAimDirection() * _aimRange, Color.red);
}

And it seems to be perfectly fine - ray is pointing at desirable direction (Screenshot_2). The objects I shoot at have collider. What can be the problem?


Hi. I’m no expert so I don’t know if I can help you, but I think the problem may be in your code. Namely in your case “return null” you are writing outside of Raycast which may be a mistake. So the script detects the objects correctly, but always returns null because your “return null” is not related to Raycast. Try to save it like this:

if (Physics.Raycast(aimStart, GetAimDirection(), out RaycastHit hit, _aimRange, _aimMask))
             {
                 return hit.collider.gameObject;
             }
else
            {
                return null;
            }

As I mentioned, I’m no expert, but I think it’s worth a try