[Unity] Unity 기초강의 내용 정리 (2-7강 ~ 2-11강)

[Unity] Unity 기초강의 내용 정리 (2-7강 ~ 2-11강)

educast 나동빈 님의 <Mobile Defence Game 제작으로 배우는 Unity 기초> 강의를 듣고 내용 정리.

———-

2-7. Function

함수(Function) : 불필요한 소스코드의 반복을 없애기 위해 특정한 기능을 정의한 것

유니티는 스크립트 단독으로는 실행이 불가하다.

스크립트를 실행시키려면 빈 오브젝트라도 만들어서 스크립트를 추가해줘야 한다.

매개변수 => 함수 => 반환값

반환자료형 함수명(매개변수) {

 명령문;

 return 반환값;

}

* 함수는 매개변수가 없을 수도 있고, 반환값이 없을 수도 있다.

1. 프로젝트 뷰에 Scripts 폴더 생성, Sprites 폴더 생성하기

2. Sprites 폴더 안에 Monster_1, Monster_2, tile1 이미지 드래그 앤 드롭으로 가져다넣기

3. Scripts 폴더 안에 FunctionTest 라는 이름의 C# 스크립트 만들기

4. 하이어라키 뷰에서 Create Empty로 빈 오브젝트를 만들고, 프로젝트 뷰의 FunctionTest 를 해당 오브젝트 위에 드래그 앤 드랍하기

(유니티는 스크립트 단독으로는 실행이 불가하다.

스크립트를 실행시키려면 빈 오브젝트라도 만들어서 스크립트를 추가해줘야 한다.)

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class FunctionTest : MonoBehaviour {

    int add(int a, int b) {

        int sum = a + b;

        return sum;

    }

 

 // Use this for initialization

 void Start () {

        Debug.Log(add(3, 7));

 }

 

 // Update is called once per frame

 void Update () {

  

 }

}

* 매개변수가 없는 함수

반환값을 void로 적는다.

* 내장 함수 : 기본적으로 제공되는 함수

* 사용자 정의 함수 : 사용자가 직접 정의하여 사용할 수 있는 함수

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class FunctionTest : MonoBehaviour {

    int add(int a, int b) {

        int result = a + b;

        return result;

    }

    int substract(int a, int b) {

        int result = a – b;

        return result;

    }

    int multiply(int a, int b) {

        int result = a * b;

        return result;

    }

    int devide(int a, int b) {

        int result = a / b;

        return result;

    }

    // Use this for initialization

    void Start () {

        Debug.Log(add(3, 7));

        Debug.Log(substract(10, 3));

        Debug.Log(multiply(5, 3));

        Debug.Log(devide(10, 3));

    }

 

 // Update is called once per frame

 void Update () {

  

 }

}

———-

2-8. Vector3와 Translate

* 벡터 : 물체에 힘을 가할 때 어느 방향으로 얼마만큼의 힘을 가하는지를 나타내는 물리적 양.

(벡터 : 크기 + 방향)

* 스칼라 : ‘크기’만을 가지고 있는 물리적 양. 단순한 숫자값이라고 생각하면 된다.

a = <2,4>

한 번 움직일 때 X 좌표로 2, Y 좌표로 4만큼 이동하는 벡터

벡터의 곱셈

a = <1,2> 에 스칼라 2를 곱한다면?

a = <2,4>

* Vector3 : Unity에서 3차원 공간에서의 벡터를 표현하기 위해 사용.

Vector3.up : 벡터 <0, 1, 0>을 의미함.

Vector3.down : 벡터 <0, -1, 0>을 의미함.

Vector3.right : 벡터 <1, 0, 0>을 의미함.

Vector3.left : 벡터 <-1, 0, 0>을 의미함.

* Translate() : Object를 특정한 벡터만큼 이동시키는 함수.

트랜스레이트 함수의 매개변수는 벡터가 들어간다고 보면 된다.

transform : 유니티 모든 오브젝트에서 제공하는 변수.

내장함수로 Translate 함수를 제공함.

참고로 gameObjec도 모든 오브젝트에서 제공하는 변수임.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class VectorTest : MonoBehaviour {

 // Use this for initialization

 void Start () {

  

 }

 

 // Update is called once per frame

 void Update () {

        transform.Translate(Vector3.right * 0.01f);

 }

}

———-

2-9. 조건문

* 조건문 : 조건에 따라서 프로그램 실행의 흐름을 결정하는 문법.

일반적으로 조건문은 if – else 문법을 사용합니다.

if (조건) {

 명령문;

} else if (조건) {

 명령문;

} else {

 명령문;

}

(1) Scripts 폴더 안에 ConditionTest 라는 이름의 C# Script 생성

(2) 빈 오브젝트를 만들어서 드래그 앤 드랍을 이용하여 ConditionTest 컴포넌트를 추가

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class ConditionTest : MonoBehaviour {

 // Use this for initialization

 void Start () {

        int a = 10;

        if (a >= 20) {

            Debug.Log(“a는 20보다 크거나 같습니다.”);

        } else if (a >= 10) {

            Debug.Log(“a는 10보다 크거나 같습니다.”);

        } else {

            Debug.Log(“a는 10보다 작습니다.”);

        }

 }

 

 // Update is called once per frame

 void Update () {

  

 }

}

조건은 다음 등과 같은 비교 연산자를 이용해서 제시할 수 있습니다.

A == B : A와 B가 일치하는 경우 TRUE, 그렇지 않으면 FALSE

A >= B : A가 B보다 크거나 같으면 TRUE, 그렇지 않으면 FALSE

A <= B : A가 B보다 작거나 같으면 TRUE, 그렇지 않으면 FALSE

여러 개의 조건을 합칠 때는 논리 연산자를 사용할 수 있습니다.

(1) (조건 1) && (조건2) : 조건 1과 조건 2과 모두 TRUE인 경우에만 TRUE

    => 앰퍼센트가 2개 붙어있는 것을 앤드 연산자 라고 한다.

(2) (조건 1) || (조건 2) : 조건 1과 조건 2 중에 하나만 TRUE이면 TRUE

* AND 연산자 테스트

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class ConditionTest : MonoBehaviour {

 // Use this for initialization

 void Start () {

        string job = “전사”;

        if (job == “전사” && level > 10) {

            Debug.Log(“환영합니다. 고급 전사님.”);

        } else {

            Debug.Log(“입장할 수 없는 던젼입니다.”);

        }

 }

 

 // Update is called once per frame

 void Update () {

  

 }

}

* OR 연산자 테스트

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class ConditionTest : MonoBehaviour {

    // Use this for initialization

    void Start() {

        string job = “전사”;

        if (job == “전사” || job == “마법사”) {

            Debug.Log(“입장할 수 있는 직업입니다.”);

        } else {

            Debug.Log(“입장할 수 없는 직업입니다.”);

        }

    }

    // Update is called once per frame

    void Update() {

    }

}

* 컴퓨터의 4칙 연산과 모듈로(%) 연산

A + B : A와 B를 더한 값.

A – B : A와 B를 뺀 값.

A * B : A와 B를 곱한 값.

A / B : A와 B를 나는 몫 값.

A % B : A와 B를 나는 나머지 값.

Empty Object에 Add Component 로 Sprite Renderer 를 추가하면 그림을 지정할 수 있다.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class ConditionTest : MonoBehaviour {

    int frame = 0;

    // Use this for initialization

    void Start() {

       

    }

    // Update is called once per frame

    void Update() {

        // 일반적으로 60 FPS 이므로 아래처럼 작성하면 1초에 한 번 수행한다.

        frame = frame + 1;

        if (frame % 60 == 0) {

            transform.Translate(Vector2.right * 1.0f);

        }

    }

}

과제

몬스터 이미지 2개를 이용해, 두 개의 몬스터 Object가 양쪽에서 서서히 다가와 부딪히는 프로그램을 작성하세요.

이 때 Collider 와 Rigidbody2D를 활용하세요.

———-

2-10. GetKey

GetKey() : 해당되는 키를 누르고 있을 경우 TRUE 값을 계속 반환합니다.

GetKeyDown() : 해당되는 키를 눌렀을 때 TRUE 값을 1번 반환합니다.

GetKeyUp() : 해당되는 키를 눌렀다가 떼었을 때 TRUE 값을 1번 반환합니다.

if (Input.GetkeyDown(KeyCode.A)) {

 Debug.Log(“A를 눌렀습니다.”);

}

Input 이라는 라이브러리 안에 있음.

(1) 프로젝트 뷰의 Scripts 폴더 안에 GetKeyTest 라는 이름의 C# 스크립트 생성

(2) Monster2에 GetKeyTest 컴포넌트를 add 처리

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class GetKeyTest : MonoBehaviour {

 // Use this for initialization

 void Start () {

  

 }

 

 // Update is called once per frame

 void Update () {

  if (Input.GetKey(KeyCode.LeftArrow)) {

            transform.Translate(Vector3.left * 0.01f);

        } else if (Input.GetKey(KeyCode.RightArrow)) {

            transform.Translate(Vector3.right * 0.01f);

        }

    }

}

과제

방향키(상, 하, 좌, 우)를 눌러서 몬스터 Object를 이동시키는 프로그램을 작성하세요.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class GetKeyTest : MonoBehaviour {

 // Use this for initialization

 void Start () {

  

 }

 

 // Update is called once per frame

 void Update () {

  if (Input.GetKey(KeyCode.LeftArrow)) {

            transform.Translate(Vector3.left * 0.01f);

        } else if (Input.GetKey(KeyCode.RightArrow)) {

            transform.Translate(Vector3.right * 0.01f);

        }

        if (Input.GetKey(KeyCode.UpArrow)) {

            transform.Translate(Vector3.up * 0.01f);

        } else if (Input.GetKey(KeyCode.DownArrow)) {

            transform.Translate(Vector3.down * 0.01f);

        }

    }

}

———-

2-11. Destory와 SetActive

Destroy(object);

게임이 진행되는 도중에 Scene에서 Object를 완전히 제거하는 함수

(슈팅게임에서 탄환, RPG 게임에서의 투사체 등)

gameObject.SetActive(true);

gameObject.SetActive(false);

게임이 진행되는 도중에 Scene에서 Object를 활성화/비활성화하는 함수

(RPG 게임에서 일정시간 지속되는 소환수 등)

(1) 프로젝트 뷰에서 DestroySetActive 라는 이름의 C# 스크립트 파일 생성

(2) 몬스터 스프라이트를 이용해 몬스터 오브젝트 생성

(3) 하이어라키 뷰의 몬스터 위로 DestroySetActive 스크립트 파일 드래그 앤 드랍하여 컴포넌트 Add 처리

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class DestroySetActive : MonoBehaviour {

    float timer = 180.0f;

 // Use this for initialization

 void Start () {

  

 }

 

 // Update is called once per frame

 void Update () {

        timer -= 1.0f;

        // 약 3초 뒤 몬스터 삭제

        if (timer <= 0) {

            Destroy(gameObject);

        }

 }

}

Time.deltaTime;

컴퓨터마다 FPS가 다른 문제를 해결하기 위해

1초를 ‘초당 프레임’만큼 나눈 값을 저장하는 변수

(예를 들어, 초당 프레임이 100회라면 Time.deltaTime이 약 0.01 정도로 산정됨)

* 간단히 말해서 Time.deltaTime 을 이용하면 컴퓨터 마다 성능이 달라도 정확한 시간(1초)를 구할 수 있다.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class DestroySetActive : MonoBehaviour {

    float timer = 3.0f;

 // Use this for initialization

 void Start () {

  

 }

 

 // Update is called once per frame

 void Update () {

        timer -= Time.deltaTime;

        // 정확히 3초 뒤 몬스터 삭제

        if (timer <= 0) {

            Destroy(gameObject);

        }

 }

}

Destory(object, 3f);

3초 뒤에 object를 Destory 한다는 의미

* 이 명령어를 사용하면 편하다.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class DestroySetActive : MonoBehaviour {

   

 // Use this for initialization

 void Start () {

        Destroy(gameObject, 3f);

 }

 

 // Update is called once per frame

 void Update () {

       

 }

}

Destory 와 SetActive의 차이

Destory 는 완전 삭제, SetActive는 비활성화 처리

기능적으로는 동일함. 씬에서 오브젝트를 다시 살릴 가능성이 있는 경우 SetActive 사용할 것.

Destroy(object);

게임이 진행되는 도중에 Scene에서 Object를 완전히 제거하는 함수

gameObject.SetActive(true);

gameObject.SetActive(false);

게임이 진행되는 도중에 Scene에서 Object를 활성화/비활성화하는 함수

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class DestroySetActive : MonoBehaviour {

    float timer = 3.0f;

 // Use this for initialization

 void Start () {

 }

 

 // Update is called once per frame

 void Update () {

        timer -= Time.deltaTime;

        // 3초 뒤 오브젝트 비활성화

        if (timer <= 0) {

            gameObject.SetActive(false);

        }

 }

}