Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

GUMI Dev

[유니티 C# 함수 기초] 변수 본문

Unity

[유니티 C# 함수 기초] 변수

GUMI Dev 2021. 11. 14. 03:34

변수는 데이터를 메모리에 저장하는 장소다. 

int level = 5; // 정수형 데이터
float strength = 15.5; // 숫자형 데이터
string playerName = "유니티"; // 문자형 데이터. 큰따옴표 필수. 
bool isFullLevel = true; // 논리형 데이터. 참 혹은 거짓. 

// 선언: 이름을 정하는 것
// 초기화: 값을 넣는 것
// 프로그래밍의 과정: 선언 > 초기화 > 호출(사용)

 

예시로 유니티 C# 스크립트에 자기소개를 작성해보았다. 

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("자기소개");

        int age = 24;
        float height = 161.1f;
        string playerName = "규미";
        bool isEwhaWomansUniversityStudent = true;
        bool isAnEngineeringStudent = false;

        Debug.Log("학생의 이름은?");
        Debug.Log("playerName");

        Debug.Log("학생의 나이는?");
        Debug.Log("age");

        Debug.Log("학생의 키는?");
        Debug.Log("height");

        Debug.Log("학생은 학교는 이화여자대학교인가?");
        Debug.Log("isEwhaWomansUniversityStudent");

        Debug.Log("학생은 공대생인가?");
        Debug.Log("isAnEngineeringStudent");
    }
}

 

콘솔창을 확인해보면 해당 스크립트는 정상적으로 실행된다.

 

 

한가지 의문점이 있다면, float의 숫자값에 그냥 숫자만을 입력하면 F접미사를 붙이라는 오류가 자꾸 뜬다는 것이다. 

확인해보니 C# 프로그래밍에서 "real 리터럴의 형식(?)"은 접미사가 필수라고 한다. 

 

  • 접미사가 없거나 "d" 또는 "D" 접미사가 있는 리터럴은 "double" 형식이다.
  • "f" 또는 "F" 접미사가 있는 리터럴은 "float" 형식이다.
  • 'm" 또는 "M" 접미사가 있는 리터럴은 "decimal" 형식이다.

 

아래는 코드는 접미사가 붙는 리터럴 형식의 예제다. 

(참고 사이트: //docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals)

double d = 3D;
d = 4d;
d = 3.934_001;

float f = 3_000.5F;
f = 5.4f;

decimal myMoney = 3_000.5m;
myMoney = 400.75M;
double d = 0.42e2;
Console.WriteLine(d);  // output 42

float f = 134.45E-2f;
Console.WriteLine(f);  // output: 1.3445

decimal m = 1.5E6m;
Console.WriteLine(m);  // output: 1500000