Example RaycastNavMesh() a tad jumbled for me

I think this RaycastNavMesh() is a little cleaner and easier to follow. Tell me what you think…

private bool RaycastNavMesh(out Vector3 target)
{
    if (Physics.Raycast(GetMouseRay(), out var rayHit))
    {
        if (NavMesh.SamplePosition(rayHit.point, out var navHit, maxNavMeshProjectionDistance, NavMesh.AllAreas))
        {
            target = navHit.position;
            var navMeshPath = new NavMeshPath();

            if (NavMesh.CalculatePath(transform.position, target, NavMesh.AllAreas, navMeshPath))
            {
                if (navMeshPath.status == NavMeshPathStatus.PathComplete)
                {
                    if (GetPathLength(navMeshPath) <= maxPathLength)
                    {
                        return true;
                    }
                }
            }
        }
    }
    target = new Vector3();
    return false;
}

Pasting in the original for comparison:

RaycastNavmesh()
        private bool RaycastNavMesh(out Vector3 target)
        {
            target = new Vector3();

            RaycastHit hit;
            bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
            if (!hasHit) return false;

            NavMeshHit navMeshHit;
            bool hasCastToNavMesh = NavMesh.SamplePosition(
                hit.point, out navMeshHit, maxNavMeshProjectionDistance, NavMesh.AllAreas);
            if (!hasCastToNavMesh) return false;

            target = navMeshHit.position;

            return true;
        }

I think I answered a similar question on a different method earlier… it’s all a matter of preference. Both methods accomplish the task, and break execution at the same time in the CLR. Some folks prefer the syntax

if([condition fails]) return;

and others prefer the syntax

if([condition succeeds]) act;

The CLR will break it down virtually the same either way. Usually its’ a matter of how comfortable you are with indenting code so many levels. About 1/2 our instructors go one way, the other half, the other. I’m neutral, I actually use both approaches, depending on needs.

I did see you’re taking advantage of the inlined variable syntax, which the original code did not do.

if(Physics.Raycast(GetMouseRay(), out var rayHit))

This was a relatively new feature at the time the course was designed, and I do believe that by the last course, Sam applies it in a few places.

I’m certainly not going to say that your method is worse, it’s structurally quite sound, and it demonstrates a complete understanding of the lesson. Being able to invert a large conditional branch is actually a good tool for future refactoring!

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

Privacy & Terms