Home > Back-end >  Mysterious C# error in Unity when trying to return switch
Mysterious C# error in Unity when trying to return switch

Time:12-20

I was following a YouTube tutorial about Minecraft-style terrain generation in Unity, and during part 10 of the tutorial, a script is written that contains a function that ends in a return x switch statement. The exact contents of the switch are as follows:

    public static Vector3Int GetVector(this Direction direction)
    {
        return direction switch
        {
            Direction.up => Vector3Int.up,
            Direction.down => Vector3Int.down,
            Direction.right => Vector3Int.right,
            Direction.left => Vector3Int.left,
            Direction.forward => Vector3Int.forward,
            Direction.backwards => Vector3Int.back,
            => throw new Exception("Invalid direction provided.")
        };
    }

Direction is an enum in a separate script that contains forward, right, backwards, left, up, and down, in that exact order. The issue is that once the code is compiled, I receive this error in Unity from DirectionExtensions.cs (the script that contains the return switch):

Assets/Scripts/Terrain/DirectionExtensions.cs(17,52): error CS8504: Pattern missing

I've tried searching for the error code and error message on Google, but the results are either reference materials such as lists of C# error messages, or unrelated Unity errors. I've found no real-world example of this error ever occurring. And no, the error is not expected, and thus the tutorial does not demonstrate how to fix it at any point. how can I resolve this error so I can continue working on my project?

CodePudding user response:

You are missing the discard to catch all cases not matched by the previous patterns:

public static Vector3Int GetVector(this Direction direction)
{
    return direction switch
    {
        Direction.up => Vector3Int.up,
        Direction.down => Vector3Int.down,
        Direction.right => Vector3Int.right,
        Direction.left => Vector3Int.left,
        Direction.forward => Vector3Int.forward,
        Direction.backwards => Vector3Int.back,
        _ => throw new Exception("Invalid direction provided.")
    };
}

Notice the underscore at

_ => throw new Exception("Invalid direction provided.")

The documentation (Pattern matching with switch) explains:

The discard pattern can be used in pattern matching with the switch expression. Every expression, including null, always matches the discard pattern.

  • Related