Unity 기본8 - C# 사용자 정의 함수 사용법

읽기 편한 코드를 위해 기능을 나눠서 쪼갠다

 

반복해서 실행시킬 부분을 쪼갠다

 

1. 함수의 선언

 

함수의 실행이 끝나고 모든 계산이 끝난 결과 리턴할 값의 데이터 타입을 알려줘야한다.

 

 

(함수의 리턴 타입) (함수명)(parameter)

{

함수 내 실행 명령

}

 

int Square(int x){

}

 

근데 이렇게만 쓰면, 리턴 타입이 int인데 리턴이 없어서 다음과 같이 빨간줄 나온다

 

 

 

x*x를 return하도록 하면 빨간줄 없어짐

 

 

 

 

참고로 함수명은 대문자로 시작하는게 C#의 관습

 

 

 

 

2. 함수 사용

 

Square(10);해서 10을 인자로 넘겨주면, 함수 내에서 int x = 10;으로 사용해서 

 

return x*x;로 x*x를 돌려준다

 

이 x라는 값은 이 함수 내에서만 사용된다

 

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

public class HelloWorld : MonoBehaviour
{

    int Square(int x)
    {
        return x * x;
    }
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(Square(10));
    }

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

    }
}

 

 

 

 

3. void

 

void Start(){} 보면 함수의 형태인데 return이 없음

 

함수를 실행을 하지만, return이 없을 때 void라고 명시함

 

물론 return문을 쓸 수 있지만, return;이라고 아무것도 return하면 안됨

 

함수는 return 만나면 끝나고 return 뒤에 있는 문장은 실행이 안된다

 

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

public class HelloWorld : MonoBehaviour
{

    int Square(int x)
    {
        return x * x;
    }

    void Like(int n)
    {
        for (int i = 0; i < n; i++)
        {
            Debug.Log("좋아요");
        }
    }

    void Subscription(int n)
    {

        for (int i = 0; i < n; i++)
        {
            Debug.Log("구독");
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        Like(3);
        Subscription(3);
    }

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

    }
}

 

 

 

 

4. 함수의 scope

 

Like() 함수에 x = 3;을 넣고, Like 내에서 n = 5;로 바꾼 다음 Like 끝나고 x를 출력해보면

 

 

 

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

public class HelloWorld : MonoBehaviour
{

    int Square(int x)
    {
        return x * x;
    }

    void Like(int n)
    {
        for (int i = 0; i < n; i++)
        {
            Debug.Log("좋아요");
        }
        n = 5;
    }

    void Subscription(int n)
    {

        for (int i = 0; i < n; i++)
        {
            Debug.Log("구독");
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        int x = 3;
        Debug.Log(x);
        Like(3);
        Debug.Log(x);
    }

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

    }
}

 

 

3에서 5로 바꿨는데, 3으로 출력됨

 

 

 

 

함수 내에서 인자 int n의 값을 바꾸더라도, 함수 밖에서는 영향을 미치지 않는다

 

값을 함수에 줬을 뿐, 변수 자체를 보낸 것은 아니다

 

함수내에서 값을 아무리 바꿔도 원본 x에는 영향을 미치지 않는다

 

마찬가지로 함수 내에서 새로운 변수를 선언했다고 하더라도, 함수 밖에서는 사용불가능하다

 

 

 

 

비슷하게, 같은 함수 내더라도 for문의 중괄호 내에서 정의된 변수도 for문 밖에서 사용 불가능하다

 

 

 

 

5. call by reference

 

함수 내에 값만 보내지 않을 수 있는데

 

void Like(ref int n)으로 ref int n으로 정의하면, 인자에 값만 보내는게 아니라, 값을 보관하고 있는 장소도 같이 보낸다

 

여기서 중요한 점은 호출할 때 Like(ref x);로 ref를 붙여서 보내줘야한다

 

 

 

 

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

public class HelloWorld : MonoBehaviour
{

    int Square(int x)
    {
        return x * x;
    }

    void Like(ref int n)
    {
        for (int i = 0; i < n; i++)
        {
            Debug.Log("좋아요");
        }
        n = 5;
    }

    // Start is called before the first frame update
    void Start()
    {
        int x = 3;
        Debug.Log(x);
        Like(ref x);
        Debug.Log(x);

    }

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

    }
}

 

 

ref로 보내면, 함수 내에서 값을 변경할 경우

 

함수 밖에서도 값이 변경되어 있다.

 

 

 

 

 

진짜 꼭 필요한 것 아니면 call by reference는 사용을 권장하지는 않는다

 

 

6. out

 

out은 함수에 일단 장소만 넘겨준다

 

그러다보니까 다음 그림과 같이, 처음에 줄 때 x = 3을 넘겨줬음에도,

 

함수 내에서 n이 할당되어 있지 않다고 한다

 

그래서 함수 처음에 n을 초기화해줘야함

 

 

 

 

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

public class HelloWorld : MonoBehaviour
{

    int Square(int x)
    {
        return x * x;
    }

    void Like(out int n)
    {
        n = 5;

        for (int i = 0; i < n; i++)
        {
            Debug.Log("좋아요");
        }

    }

    // Start is called before the first frame update
    void Start()
    {
        int x = 3;
        Debug.Log(x);
        Like(out x);
        Debug.Log(x);

    }

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

    }
}

 

 

 

처음에 3을 out으로 넘겨주고, 함수 처음에 n = 5로 초기화 한 다음 사용하면

 

실제로 x가 5로 바뀌어있다는 것을 볼 수 있다

 

 

 

 

 

ref와 마찬가지로 반드시 필요한 것이 아니면 사용을 권장하지는 않는

 

 

7. default parameter

 

함수 parameter에 기본값을 지정함

 

인자로 값을 넘겨주지 않으면 기본값을 사용함

 

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

public class HelloWorld : MonoBehaviour
{

    void Like(string m, int n = 3)
    {
        for (int i = 0; i < n; i++)
        {
            Debug.Log(m);
        }

    }

    // Start is called before the first frame update
    void Start()
    {

        Like("좋아요");

    }

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

    }
}

 

 

 

 

 

당연하지만 실제 값을 지정해서 넘겨주면, default값은 무시함

 

Like("좋아요",4);로 하면 좋아요가 4번 나온다

 

 

8. params

 

개수가 정해지지 않은 parameter를 넘기고 싶을 때 parameter 앞에 params라고 붙여준다

 

파이썬에서 *args하는 것처

 

void Like(params string[] m) {};

 

Like("아야카","라이덴","치오리");

 

이렇게 실제로 배열로 넘긴건 아니고 개수가 정해지지 않은 여러개의 string을 넘겼는데,

 

m은 string배열로 들어온다

 

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

public class HelloWorld : MonoBehaviour
{

    void Like(params string[] message)
    {
        foreach( string s in message)
        {
            Debug.Log(s);
        }
    }

    // Start is called before the first frame update
    void Start()
    {

        Like("아야카","라이덴","치오리");

    }

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

    }
}

 

 

 

 

다음과 같이 특히 내가 원하는 건 정수로 넘기고 싶을 때

 

void Like(int x, params string[] m){};

 

Like(3, "아야카", "라이덴","치오리");

 

x에는 3이 들어가고 m에는 ["아야카","라이덴","치오리"] 배열로 들어간다

 

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

public class HelloWorld : MonoBehaviour
{

    void Like(int x, params string[] message)
    {
        Debug.Log(x);
        foreach( string s in message)
        {
            Debug.Log(s);
        }
    }

    // Start is called before the first frame update
    void Start()
    {

        Like(3,"아야카","라이덴","치오리");

    }

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

    }
}

 

 

TAGS.

Comments