error "not all code paths return a value" in a function

Sorry, because I know this has been asked a hundred times before. But I have no idea why this code is giving me this error, because I cant see any path it could take for it to not return a value…

Vector3 roadSnapping (Vector3 point){
	//goes through every road in the array, checks if snapping to end point
	for (int i = 0; i < controlPoints.GetLength (0); i++) {
		if (Vector3.Distance (controlPoints [i, 0], point) < 10) {
			return controlPoints [i, 0];
		} else {
			return point;
		}
	}
}

The “for” loop is unavoidable, it will always go through this, unless the length is less than 1, however if I put a “return point;” after the loop, I get an error message calling it unreachable code.
thanks for any help u can give :slight_smile:

As you said yourself the for loop only enters if the length of your array is greater than 0. Actually it doesn’t matter what condition you use in the for loop unless it’s a constant expression which can be determined at compile time which isn’t the case here. A method that has a return value must always return a value. So you can’t just leave the method without a “return” statement.

So you have to have a return after the for loop. I doubt that you get an “unreachable code” error unless you do something else wrong. This should work:

Vector3 roadSnapping (Vector3 point)
{
    for (int i = 0; i < controlPoints.GetLength (0); i++) {
        if (Vector3.Distance (controlPoints [i, 0], point) < 10)
        {
            return controlPoints [i, 0];
        }
    }
    return point;
}

The else in your code doesn’t make much sense as you would always exit the for loop in the first iteration so the for loop would be pointless.

Note: My example will return the first point which is closer than 10 units to the test point. Keep in mind that doesn’t have to be the closest point. We don’t know what you actually want to do so we can’t suggest a specific solution.