jae_coding

[유니티로 배우는 C#] 함수 본문

C#

[유니티로 배우는 C#] 함수

재코딩 2022. 7. 19. 09:22
반응형

함수의 기능

예제 함수

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


public class Unity_lecture : MonoBehaviour
{
    int intValue;
    float floatValue = 10.1f;

    void FloatToInt(){
        intValue = (int)floatValue;
    }
    void Start()
    {
        FloatToInt();
        print(intValue);
    }

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

예제의 코드에서는 함수가 1번밖에 사용되어지지 않았지만, 함수가 여러변 그리고 함수의 내용이 길게 된다면 반복되는 작업을 간편하게 코드가 구현될 수 있도록 도와줄 수 있다.

 

매개변수가 있는 함수

    float floatValue = 10.1f;
    float2 floatValue2 = 20.5f;

    void FloatToInt(float _parameter){
        intValue = (int)_parameter;
        print(intValue);
    }
    void Start()
    {
        FloatToInt(floatValue); //10출력
        FloatToInt(floatValue2); //20출력
    }

입력을 받아 처리하는 함수를 만들 수 있다.

 

디폴트가 있는 함수

    float floatValue = 10.1f;
    float2 floatValue2 = 20.5f;

    void FloatToInt(float _parameter, string _stringParm = "default){
        intValue = (int)_parameter;
        print(intValue);
        print(_stringParm);
    }
    void Start()
    {
        FloatToInt(floatValue, "Test"); //10, Test출력
        FloatToInt(floatValue2); //20, default출력
    }

반환값이 있는 함수

    int FloatToInt(float _parameter, float _parameter2){
        intValue = (int)(_parameter + _parameter2);
        print(intValue);

        return intValue;
    }
    void Start()
    {
        Value = FloatToInt(floatValue, floatValue2);
        print(Value);
    }

 

함수의 이름을 선언하기전에 반환을 할 타입을 먼저 결정해야한다.  위 코드의 경우에는 Integer type을 반환하여 주기위해서 FloatToInt함수를 int타입으로 return해주는 함수를 만든 것이다.

 

강의자료: 케이디 유튜브

반응형
Comments