heylo 2022. 12. 22. 02:50

여기서는 코드 흐름을 통제하는 방법을 배웁니다.

지금까지는 모든 코드를 위에서 아래로 실행했습니다.

 

하지만 제어문을 사용하면 조건에 따라

특정 코드의 실행 여부나 실행 순서를 변경할 수 있습니다.

 

제어문에는 분기를 결정하는 조건문 (if문)

수행을 여러 번 반복하는 반복문(for 문, while 문)이 있습니다.


4.7.1 if 문

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

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int love = 100;
        if (love > 70)
        {
            Debug.Log("굿엔딩 히로인과 사귀게 되었다!");
        }
        if (love <= 70)
        {
            Debug.Log("배드엔딩 히로인에게 차였다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


4.7.2 비교 연산자


4.7.3 if .. else 문

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

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int love = 100;
        if (love > 70)
        {
            Debug.Log("굿엔딩 히로인과 사귀게 되었다!");
        }
        else
        {
            Debug.Log("배드엔딩: 히로인에게 차였다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


4.7.4 else if 문

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

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int love = 100;

        if (love > 90)
        {
            // love가 90보다 큰 경우
            Debug.Log("트루엔딩: 히로인과 결혼했다!");
        }
        else if (love > 70)
        {
            // love가 70보다 크고 90보다 작거나 같은 경우
            Debug.Log("굿엔딩 히로인과 사귀게 되었다!");
        }
        else
        {
            // love가 70보다 작거나 같은 경우
            Debug.Log("배드엔딩: 히로인에게 차였다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


4.7.5 논리 연산자

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

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int age = 11;

        if (age > 7 && age < 18)
        {
            Debug.Log("의무 교육을 받고 있습니다.");
        }
        if(age < 13 || age > 70)
        {
            Debug.Log("일을 할 수 없는 나이입니다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


4.7.6 for 문

for문은 조건이 참일 동안 처리를 반복합니다.

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

public class HelloCode : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < 10; i++)
        {
            Debug.Log(i + " 번째 순번입니다.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}