Search code examples
c#unity-game-engineswitch-statementvector2

I want to make a method that returns the position the player is facing


I made a simple script to check what position the player is facing and put that in my animator

1 = up

2 = right

3 = down

4 = left

private Vector2 velocity;
private Animator animator;
private int direction;
private void Awake() {
    animator = GetComponent<Animator>();

}
void Update(){
    velocity.x = Input.GetAxisRaw("Horizontal");
    velocity.y = Input.GetAxisRaw("Vertical");
    switch(velocity){
        case Vector2(0,1):
        direction = 1;
        break;
        case Vector2(1,0):
        direction = 2;
        break;
        case Vector2(0,-1):
        direction = 3;
        break;
        case Vector2(-1,0):
        direction = 4;
        break;
    }
    animator.SetFloat("Facing",direction);

then I get the error

Assets/Scripts/PlayerMovement.cs(21,25): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'Vector2', with 2 out parameters and a void return type.


Solution

  • I believe your issue comes with how you are trying to use your switch statement as Vector(1,0) is attempting to call a function not actually reference the value you are looking a viable alternative is to use when like in the following example

                    case Vector2 v when v.Equals(Vector2.up):
                        Debug.Log("Up");
                        break;
                    case Vector2 v when v.Equals(Vector2.left):
                        Debug.Log("Left");
                        break;
                    case Vector2 v when v.Equals(Vector2.back):
                        Debug.Log("Back");
                        break;
                    case Vector2 v when v.Equals(Vector2.right):
                        Debug.Log("Right");
                        break;
    

    I'm also using the shorthand up, left, right and down instead of defining the values manually