GUMI Dev
[유니티 C# 함수 기초] 그룹형 변수 본문
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 오류라고도 한다. )
크기를 벗어난 탐색은 오류가 발생하기 때문이다.
'Unity' 카테고리의 다른 글
[유니티 Input] 마우스 입력 (0) | 2021.11.17 |
---|---|
[유니티 Input] 키보드 입력 (0) | 2021.11.17 |
[유니티 게임 오브젝트 흐름] 초기화 - 프레임(물리, 로직) - 해제 (0) | 2021.11.15 |
[유니티 C# 함수 기초] 변수 (0) | 2021.11.14 |
[유니티 C# 시작하기] (1) | 2021.11.13 |