"Not all Code Paths Return a Value"

I am unable to get rid of the error in this function, even after using the code provided in the references. It’s throwing the error of “not all code paths return a value”. I’m not sure what his means. If anyone could help me spot the error that would be great.

    {
        List<GridPosition> validGridPositionList = new List<GridPosition>();

        GridPosition unitGridPosition = unit.GetGridPosition();

        for (int x = -maxShootDistance; x <= maxShootDistance; x++)
        {
            for (int z = -maxShootDistance; z <= maxShootDistance; z++)
            {
                GridPosition offsetGridPosition = new GridPosition(x, z);
                GridPosition testGridPosition = unitGridPosition + offsetGridPosition;

                if (!LevelGrid.Instance.IsValidGridPosition(testGridPosition))
                {
                    continue;
                }

                int testDistance = Mathf.Abs(x) + Mathf.Abs(z);
                if (testDistance > maxShootDistance)
                {
                    continue;
                }

                if (!LevelGrid.Instance.HasAnyUnitOnGridPosition(testGridPosition))
                {
                    // Grid Position is empty, no Unit
                    continue;
                }

                Unit targetUnit = LevelGrid.Instance.GetUnitAtGridPosition(testGridPosition);

                if (targetUnit.IsEnemy() == unit.IsEnemy())
                {
                    // Both Units on same 'team'
                    continue;
                }

                validGridPositionList.Add(testGridPosition);
            }

            return validGridPositionList;
        }
    }

The return statement is within the first for loop. Because it’s technically possible to have maxShootDistance of 0, the compiler considers that the code would exit in that event.
Change the end of the method to look like this:

                validGridPositionList.Add(testGridPosition);
            }
         }
            return validGridPositionList;
    }

I swear, it’s always the brackets. Thank you so much.

For others, it’s the ! marks. :slight_smile: This case with the brackets is a hard one to spot.

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

Privacy & Terms