본문 바로가기

Unity(기록용)/Unity 기초

Unity 반복문

유니티의 반복문에는 4가지가 있다.

For

1
2
3
4
for(int i = 0; i < iterationCount; i++)
{
      Debug.Log("반복");
}
cs

첫 번째 식은 int i=0은 1번 호출되며 i를 0으로 선언해 준다.

이후 두 번째 식 i <iterationCount를 통해 for루프가 반복될 조건을 정해줄 수 있다.

마지막으로 i++은 루프가 실행될 때마다 i의 값을 1씩 증가시켜준다.

만약 iterationCount가 3이라면 로그창에 반복이 3번 출력된다.

Foreach

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
using System.Collections;
using System.Collections.Generic;
using UnityEditor.UI;
using UnityEngine;
 
public class While : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int i = 0;
        while(gameObject.activeSelf)
        {
            
            Debug.Log("오브젝트가 켜져있습니다");
 
            i++;
            if (i == 1000)
            {
                gameObject.SetActive(false);
            }
        }
    }
 
}
 
cs

foreach(변수 선언 in Array나 List) Foreach는 Array나 List에 주로 사용한다. 위의 코드에서 설명하면 targets에 있는 각 요소들을 Vector3 target을 선언해서 루프가 실행된다. 로그창에는 아래와 같이 Vector3.zero와 one, up의 값이 출력된다. 

While

using System.Collections;
using System.Collections.Generic;
using UnityEditor.UI;
using UnityEngine;

public class While : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int i = 0;
        while(gameObject.activeSelf)
        {
            
            Debug.Log("오브젝트가 켜져있습니다");

            i++;
            if (i == 1000)
            {
                gameObject.SetActive(false);
            }
        }
    }

}

While문에서는 조건이 false가 될 때까지 루프를 실행합니다. 조건인 activeSelf 오브젝트가 활성화 상태입니다. 만약 오브젝트가 켜져 있으면 로그에 출력이 됩니다. 1000번이 수행될 경우 오브젝트의 활성화상태를 false로 바꿔주고 루프에서 탈출합니다.

Do-While

using System.Collections;
using System.Collections.Generic;
using UnityEditor.UI;
using UnityEngine;

public class DoWhile : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int i = 0;
        do
        {

            Debug.Log("오브젝트가 켜져있습니다");

            i++;
            if (i == 1000)
            {
                gameObject.SetActive(false);
            }
        } while (gameObject.activeSelf);
    }

}

Do-While은 While과 비슷하나 루프가 실행되고 조건을 판단하면 false면 종료시킵니다. 그러니 While과는 다르게 1번은 루프가 실행됩니다.

Break

break가 수행되면 즉시 루프를 탈출합니다.

 

  int i = 0;
        while(true)
        {
            i++;
            if (i == 10000)
            {
                break;
            }
        }

while(true)가 되면 무한반복 상태가 됩니다. 항상 참인 상태니 이때 i가 1만 일 때 break 시켜주면 1만 번만 수행되고 꺼집니다. 원래는 무한반복 상태가되면 유니티가 뻗는데, 만약 무한반복할꺼같은 코드에 보통 1만번 이상 수행 시 예외처리 시켜준다거나 반복문을 꺼주는 식으로 하면 뻗는 걸 예방할 수 있습니다.

Continue

void DetonateActiveTargets(Target[] targets)
{
   for (int i = 0; i < targets.Length; i++)
   {
       Target currentTarget = targets[i];
       if(!currentTarget.isActive)
           continue;
       currentTarget.Detonate();
   }
}

continue가 수행될 경우 해당 루프에서 다음코드를 수행하지 않고 탈출합니다. 위의 코드에서는 타깃이 활성화 상태가 이면 Detonate가 호출됩니다. 활성화 상태가 아니라면 continue가 수행되어 탈출하고 다음 루프로 넘어갑니다.

아래는 Unity Loop tutorial 사이트입니다.

https://learn.unity.com/tutorial/loops-z2b

 

Loops - Unity Learn

How to use the For, While, Do-While, and For Each Loops to repeat actions in code.

learn.unity.com

 

'Unity(기록용) > Unity 기초' 카테고리의 다른 글

유니티 Life Cycle  (1) 2023.06.19