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:50

1. Array(배열)

먼저 간단하게 김밥천국 메뉴를 만들어보았다. 

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("김밥천국");

        // 배열: 가장 기본적인 고정형 그룹형 변수
        string[] qimbapHeaven = { "떡볶이", "순대", "오뎅", "김밥" };

        Debug.Log("김밥천국 메뉴");
        Debug.Log("qimbapHeaven[0]");
        Debug.Log("qimbapHeaven[1]");
        Debug.Log("qimbapHeaven[2]");
        Debug.Log("qimbapHeaven[3]");
    }
}

 

김밥천국 메뉴에서 가격에 대한 정보를 추가했다. 

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("김밥천국");

        // 배열: 가장 기본적인 고정형 그룹형 변수
        string[] qimbapHeaven = { "떡볶이", "순대", "오뎅", "김밥" };
        int[] qimbapHeavenPrice = new int[4];
        qimbapHeavenPrice[0] = 4500;
        qimbapHeavenPrice[1] = 5500;
        qimbapHeavenPrice[2] = 3500;
        qimbapHeavenPrice[3] = 2500;

        Debug.Log("김밥천국 메뉴의 가격");
        Debug.Log(qimbapHeavenPrice[0]);
        Debug.Log(qimbapHeavenPrice[1]);
        Debug.Log(qimbapHeavenPrice[2]);
        Debug.Log(qimbapHeavenPrice[3]);
    }
}

 

확인해보니 콘솔창에서 해당 스크립트가 정상적으로 작동한다. 

 

 

2. List

이번에는 내가 좋아하는 것을 List로 나타내보았다. 

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        List<string> myFavorites = new List<string>();
        myFavorites.Add("커피마시기");
        myFavorites.Add("음악듣기");

        Debug.Log("내가 좋아하는 것");
        Debug.Log(myFavorites[0]);
        Debug.Log(myFavorites[1]);
    }
}

 

콘솔창에서 정상적으로 작동. 

 

Array와는 달리 List는 안에 있는 데이터를 추가하거나 삭제할 수 있다. 

Array는 크기가 고정된(fixed) 상태인 반면, List는 크기가 고정되지않고 자유롭다. 

List는 Add, Remove, Clear와 같은 메소드를 사용할 수 있다. 

 

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        List<string> myFavorites = new List<string>();
        myFavorites.Add("커피마시기");
        myFavorites.Add("음악듣기");

        myFavorites.RemoveAt(0);

        Debug.Log("내가 좋아하는 것");
        Debug.Log(myFavorites[0]);
        Debug.Log(myFavorites[1]);
    }
}

 

"커피마시기"를 삭제해보았다. 

 

 

"ArgumentOutOfRangeException" 에러가 뜬다. (Index 오류라고도 한다. )

크기를 벗어난 탐색은 오류가 발생하기 때문이다.