프로그래밍/Unity C#

[Unity] Tutorial 05 - Beginner Gameplay Scripting (Enumerations)

FireflyStudioX 2019. 11. 4. 13:53

목표

  • enum 사용방법에 대해 알아보자

enum

  • enum는 상수 집합으로 구성된 열거형 데이터를 선언하는데 사용되는 키워드 이다.

  • 초기값이 없다면 순서대로 RED(0), YELLOW(1), GREEN(2), BLUE(3)의 값을 가진다.

    enum Color{ RED, YELLOW, GREEN, BLUE }
  • 만약 초기값을 부여한다면, 0대신 초기값을 시작 값으로 가진다.

    enum Color{ RED=100, YELLOW, GREEN, BLUE }
  • 혹은 원하는 값으로 초기화 할 수 있다. (다만 열거형의 사용 목적상, 초기값을 부여하지 않고 사용하는 것이 좋다.)

    enum Color {RED=100, YELLOW=103, GREEN=55, BLUE=17}

예시

  • 다음은 4가지 색중 1개를 선택하여, 선택한 색상을 출력하는 예시이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnumScript : MonoBehaviour
{
    enum MyColor { RED, YELLOW, GREEN, BLUE };

    // Start is called before the first frame update
    void Start()
    {
        SelectMyColor(MyColor.RED);
    }

    // Update is called once per frame
    void Update()
    {

    }

    void SelectMyColor(MyColor myColor)
    {
        switch (myColor)
        {
            case MyColor.RED:
                Debug.Log("RED!!");
                break;

            case MyColor.GREEN:
                Debug.Log("GREEN!!");
                break;

            case MyColor.YELLOW:
                Debug.Log("YELLOW!!");
                break;

            case MyColor.BLUE:
                Debug.Log("BLUE!!");
                break;

            default:
                Debug.Log("UNKNOWN!!");
                break;
        }
    }

}