나아가기

[Unity] 함수 본문

Unity_Metaverse

[Unity] 함수

channnnii 2022. 6. 22. 11:20

반복 조건문

1. while(조건식) : 조건식이 참인 동안 블록 안의 문장을 계속 실행하게 합니다.

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

public class Controll : MonoBehaviour
{
    void Start()
    {
        int jump;
        jump=10;

        while(jump > 0)
        {
            Debug.Log("바둑이가 " + (10-jump) + "번 점프합니다.");
            jump--;
        }
    }

    void Update()
    {

    }
}

 

unity로 돌아가 실행을 시키면,  

2. do while 반복문 : while반복문과 비슷하지만, 조건 비교 부분이 마지막에 위치합니다.

                                따라서 실행할 문장이 무조건 한번은 실행되게 됩니다.

 

3. for 반복문 : for(초기식; 조건식; 증감식;) { 실행할 문장들 }

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

public class Controll : MonoBehaviour
{
    void Start()
    {
        for(int i=0; i < 10; i++)
        {
            Debug.Log("바둑이가 " + (i+1) + "번 점프를 합니다.");
        }
    }

    void Update()
    {

    }
}

unity로 돌아가 실행을 시키면,

 

4. 배열 : 여러번 반복되는 같은 자료형의 값을 묶어서 배열을 만들면, 반복문을 이용해 간편하게 일을 처리할 수 있습니다.

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

public class Controll : MonoBehaviour
{
    void Start()
    {
        string[] foods = {"뼈다귀", "사료", "개껌", "사탕"};
        
        for(int i =0; i<4; i++)
        {
        	Debug.Log(foods[i]);
        }
    }

    void Update()
    {

    }
}

unity로 돌아가 실행을 시키면,

 

 

 

함수란? 

어떤 일을 처리하게 위해 미리 지정된 동작을 한군데 모아 놓은 것이 함수이다.

기능에 따라 여러 개의 함수를 만들어 사용하면 전체 코드를 읽기 쉬워질 뿐 아니라, 사용과 수정이 쉬워진다.

 

1. 함수 기능 알아보기_ 어떤 두개의 수를 넣으면 합을 구해주는 Add( ) 함수를 정의한 것입니다.

int Add(int a, int b)
{
	int sum = a+b;
	return sum;
}

void Start()
{
	int sum = Add(3, 5);
	Debug.Log(sum);
}

 

 

 

2. 함수와 반복문을 모두 활용한 예시

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

public class Controll : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        string[] foods = { "뼈다귀", "사료", "개껌", "사탕" };

        for(int i = 0; i < 4; i++)
        {
            Eat(foods[i]);
            Jump(i + 1);
        }
    }

    void Jump(int jump)
    {
        for(int i=0; i<jump; i++)
        {
            Debug.Log("바둑이가" + (i + 1) + "번 점프를 합니다.");
        }
    }
    void Eat(string food)
    {
        Debug.Log("바둑이가" + food + "를 먹습니다.");
    }

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

unity로 돌아가면,

 

Comments