Unity, C#
[Unity C#] 변수와 자료형, 대입 연산자, 조건문, 반복문
소형
2022. 10. 11. 13:52
반응형
기초 정리
변수와 자료형
변수 : 변하는 수
자료형 : 자료의 형태 ( int, float, double 등)
변수의 선언은 (액세스 한정자) 자료형 변수 = 값; 의 방식으로 할 수 있다. ex) public int score = 100;
액세스 한정자 :
public | 접근제한 없음 |
private | 해당 스크립트 내에서만 접근 가능 |
protected | 해당 스크립트와 해당 스크립트를 상속받은 자식 스크립트에서 접근 가능 |
대입 연산자
" = "
우측의 값을 좌측의 변수에 넣는 연산자.
변수 형식과 값의 형식이 같아야 한다. (포함할 수 있어야 한다.)
스크립트를 통하여 변수에 게임 오브젝트를 넣어줄 수 있는데 만약 하이라키에 있는 Circle을 게임오브젝트에 할당시키고 싶다면 아래의 코드를 통하여 할당할 수 있다.
[SerializeField]
private GameObject gameObj;
void Start()
{
gameObj = GameObject.Find("Circle");
}
혹은 프로젝트 내의 Prefab 등을 넣고 싶다면 Resources 폴더에 접근하여 가져오면 된다.
[SerializeField]
private GameObject gameObj;
void Start()
{
gameObj = Resources.Load<GameObject>("파일명");
}
조건문
조건에 따라 실행이 달라지는 문장
if문
if(score < 100) // 점수가 100점보다 낮다면
Debug.Log("Lose");
else // 아니면
Debug.Log("Win");
switch문
int type = 3;
switch (type)
{
// type값이 1이라면
case 1:
Debug.Log("1");
break;
case 2:
Debug.Log("2");
break;
case 3:
Debug.Log("3");
break;
default:
Debug.Log("?");
break;
}
게임 개발을 할 때 switch문과 함께 enum이라는 열거형을 자주 사용하게 된다.
열거형이란 서로 연관된 상수들의 집합이라고 부르는데 Switch문과 함께 아래 코드처럼 사용할 수 있다.
enum형식
public enum MonsterType { Zombie, Alien, Plant }
public class Enum : MonoBehaviour
{
public MonsterType type = MonsterType.Zombie;
void Start()
{
Debug.Log(type.ToString());
}
}
switch문 활용
public enum MonsterType { Zombie, Alien, Plant }
public class Enum : MonoBehaviour
{
public MonsterType type = MonsterType.Zombie;
void Start()
{
switch (type)
{
case MonsterType.Zombie:
Debug.Log("Zombie");
break;
case MonsterType.Alien:
Debug.Log("Alien");
break;
case MonsterType.Plant:
Debug.Log("Plant");
break;
}
}
}
반복문
반복적인 명령을 수행하는 문법.
While, For, Foreach문 등이 있다.
While문
public class Example : MonoBehaviour
{
private void Start()
{
int a = 0;
while (a < 10) // a가 10이 될 때까지 10번 반복
{
Debug.Log("Monster!");
a++;
}
}
}
For문
private void Start()
{
for(int i=0; i < 10; i++) // i가 10이 될 때까지 10번 반복
{
Debug.Log("Monster!");
}
}
Foreach문 : 배열에 있는 모든 요소들에 대해 반복적인 명령을 수행할 때 사용하는 반복문
public class Example : MonoBehaviour
{
public GameObject[] objArr = new GameObject[3];
private void Start()
{
foreach(GameObject obj in objArr)
{
obj.SetActive(false);
}
}
}
반응형