목표

  • switch 사용법에 대해 알아보자.

switch

  • switch는 정의된 case에 따라 값을 리턴하는 조건문이다.
  • 만약 정의되지 않은 값이 들어온다면 default에서 처리한다.
  • 보통 복잡한 조건이 필요한 경우 if-else문을 사용하고, 간단한 조건의 경우 switch문을 사용한다.

예시

  • 다음은 IDLE, WALK, RUNG, CODING, SLEEP의 상태를 정의하고, 입력값에 따라 상태를 업데이트하는 예제이다.
  • 만약 정의되지 않은 값이 들어온다면 default 키워드를 사용하여 CODING이 입력되도록 설정하였다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchScript : MonoBehaviour
{
    enum State { IDLE, WALK, RUNG, CODING, SLEEP };

    private State currentState;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            StateChange(0);
        }

        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            StateChange(1);
        }

        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            StateChange(2);
        }

        if (Input.GetKeyDown(KeyCode.Alpha4))
        {
            StateChange(3);
        }

        if (Input.GetKeyDown(KeyCode.Alpha5))
        {
            StateChange(4);
        }

        if (Input.GetKeyDown(KeyCode.Alpha6))
        {
            StateChange(5);
        }
    }

    void StateChange(int state)
    {
        switch (state)
        {
            case 0:
                Debug.Log("IDLE!!");
                currentState = State.IDLE;
                break;

            case 1:
                Debug.Log("WALK!!");
                currentState = State.WALK;
                break;

            case 2:
                Debug.Log("RUNG!!");
                currentState = State.RUNG;
                break;

            case 3:
                Debug.Log("CODING!!");
                currentState = State.CODING;
                break;

            case 4:
                Debug.Log("SLEEP!!");
                currentState = State.SLEEP;
                break;

            default:
                Debug.Log("DEFAULT CODING!!");
                currentState = State.CODING;
                break;
        }
    }
}
  • 만약 0, 1, 2 case에 대해 동일한 상태로 처리하고 싶은 경우 마지막 조건에 break;를 선언하면 된다.

  • 또한 특정 case에서 더이상 아래 case를 비교해볼 필요가 없는 경우 return;을 사용하면 된다.

    void StateChange(int state)
    {
      switch (state)
      {
          case 0:
          case 1:
          case 2:
              Debug.Log("0 or 1 or 2");
              break;
          case 3:
              Debug.Log("3");
              return;
          case 4:
              Debug.Log("4");
              break;
          default : 
              Debug.Log("DEFAULT!!");
              break;
      }
    }

+ Recent posts