본문 바로가기
카테고리 없음

[코딩일기] C# 타입 캐스팅

by mania2321 2024. 7. 17.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Helloworld_2 : MonoBehaviour
{
    // enum 열거

    enum ProjectileKind         // 열거. enum 타입을 쓰는 이유는, 말로 써 있어야 코드를 읽기가 더 편하기 때문
    {
        Arrow,                  // Arrow = 1 이라고 하면 이건 인덱스 값이 1이 되는거임
        Bullet,                 // Bullet = 2 라고 하면 이건 인덱스 값이 2가 되는거고
        Missile                 // Missile = 0 이라고 하면 이건 인덱스 값이 0이 되겠지?
    }

    

    void Start()
    {
        ProjectileKind kind;

        // kind = ProjectileKind.Arrow;        // 투사체의 종류는 화살이라는 뜻
        kind = (ProjectileKind)1;              // 1을 타입 캐스팅 해서 kind 에 집어 넣으면 총알이 들어감
        
        switch(kind)
        {
            case ProjectileKind.Arrow:
                Debug.Log("화살 입니다.");
                break;

            case ProjectileKind.Bullet:
                Debug.Log("총알 입니다.");
                break;

            case ProjectileKind.Missile:
                Debug.Log("미사일 입니다");
                break;
        }
        // Debug.Log((int)kind);       // enum 타입은 int 로 변환이 가능. 이게 타입 캐스팅. 뒤에 있는 변수의 자료형을 변환하는 것.
        Debug.Log(kind);
    }
}

댓글