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

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

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

———-

2-16. Acceess Modifier

접근 한정자(Access Modifier)

public : 다른 스크립트에서 접근할 수 있도록 만들 때 사용

private : 현재 스크립트에서만 접근할 수 있도록 만들 때 사용

1. 프로젝트 뷰에 AcceessModifierTest 라는 이름의 C# 스크립트 생성하기

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class AccessModifierTest : MonoBehaviour {

    public string nickname;

    public int HP;

    private bool timerEnded = false;

    float timer = 3.0f;

   

 void Start () {

  

 }

 

 void Update () {

        // 정확히 3초 뒤 실행

        timer -= Time.deltaTime;

        if (timer <= 0 && timerEnded == false) {

            Debug.Log(“이름 : ” + nickname);

            Debug.Log(“체력 : ” + HP);

            timerEnded = true;

        }

 }

}

2. 좌상단 하이어라키 뷰의 캐릭터1(당근 캐릭터) 위에 드래그 앤 드롭하여 컴포넌트 add 처리하기.

3. 우측 인스펙터 뷰에서 public 변수들의 값을 볼 수 있다.

4. 스크립트 내부에 public 변수 값을 할당하더라도,

인스펙터 뷰에 입력한 변수 값이 우선된다.

예를 들어

public string nickname = “홍길동”;

public int HP = 200;

이라고 입력하더라도,

인스펙터 뷰에서 nickname 값을 “홍길동2”, HP 값을 300 을 대입하면

인스펙터 뷰의 값을 따른다.

(게임 실행 시 로그에 홍길동2와 300이 찍힘)

접근 한정자의 개념은 변수만이 아니라 함수에도 적용될 수 있다.

AccessModifierTest 스크립트에 아래 함수를 추가한다.

 public void Damaged(int power) {

        HP -= power;

        Debug.Log(“남은 체력 : ” + HP);

    }

OnCollisionTest 스크립트의 OnCollisionEnter2D 함수 내용을 수정한다.

참고로 OnCollisionTest 스크립트도 AccessModifierTest 처럼 캐릭터1(당근 캐릭터)에 부여된 스크립트이다.

 private void OnCollisionEnter2D(Collision2D other) {

        // 타일은 제거하지 않는다.

        if (other.gameObject.tag == “Monster”) {

            // 주인공과 닿은 오브젝트를 파괴한다.

            Destroy(other.gameObject);

            gameObject.GetComponent<AccessModifierTest>().Damaged(50);

        }

    }

 

캐릭터의 키입력 바꾸기

GetComponentAddForce 스크립트 내용 수정

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class GetComponentAddForce : MonoBehaviour {

    public float jumpPower = 200.0f;

    public KeyCode keyLeft;

    public KeyCode keyRight;

    public KeyCode keyJump;

    // Use this for initialization

    void Start () {

    }

 

 // Update is called once per frame

 void Update () {

        if (Input.GetKey(keyLeft)) {

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

        } else if (Input.GetKey(keyRight)) {

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

        }

        if (Input.GetKeyDown(keyJump)) {

            GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpPower);

        }

    }

}

이제 인스펙터 뷰에서 jumpPower, keyLeft, keyRight, keyJump 을 수정해본다.

요약

public 은 다른 스크립트에서 접근 가능, private 은 현재 스크립트에서만 접근 가능

———-

2-17. OnCollision과 Access Modifier 실습

GetComponent의 사용

* 어떠한 오브젝트에 속한 컴포넌트에 접근하기 위한 목적으로 사용함

* 대부분 모든 컴포넌트는 GetComponent를 활용함

(모든 오브젝트에 내장된 트랜스폼 컴포넌트는 예외임)

* 특정한 오브젝트의 중력값을 0 으로 만들어보는 실습

GetComponent<RigidBody2D>().gravityScale = 0;

Prefab

* Prefab은 프로젝트 전체에서 사용할 수 있는 Object의 “틀”

* Prefab을 사용해 Scene에 배치한 Object는 Prefab의 특성을 똑같이 가진 “복제품”

* 어떤 작업을 수행할 때, 그 대상이 Object냐 Prefab이냐는 큰 차이

* 혼란을 방지하기 위해 가급적 다른 이름을 사용하거나, 폴더를 따로 생성해서 관리

1. 프로젝트 뷰에 BulletScript 라는 이름의 C# 스크립트 생성

2. 하이어라키 뷰의 Bullet_1 위에 드래그앤드랍하여 컴포넌트 Add 처리

3. 충돌감지를 위해 Bullet_1에 Box Collider 2D를 추가하기

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BulletScript : MonoBehaviour {

    float speed = 3.0f;

   

 void Start () {

  

 }

 

 void Update () {

        transform.Translate(Vector3.right * speed * Time.deltaTime);

 }

    private void OnCollisionEnter2D(Collision2D other) {

        if (other.gameObject.tag == “Monster”) {

            // 몬스터가 사라지도록 처리

            Destroy(other.gameObject);

            // 총알이 사라지도록 처리

            Destroy(gameObject);

        }

    }

}

4. 총알에 중력 적용을 위해 RigidBody2D 를 추가

* 메모리 관리를 위한 처리

(1) 화면 가장자리에 벽을 만들고 벽에 충돌됐을 때 총알 제거

(2) 일정 시간이 지나면 총알 제거

5. 하단의 타일에 Tag를 추가 (Tile 이라는 이름으로 지정)

6. 타일 크기를 좌우로 늘려서 총알이 꼭 닿도록 조정

7. 코드 수정

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BulletScript : MonoBehaviour {

    float shotPower = 500.0f;

   

 void Start () {

        GetComponent<Rigidbody2D>().AddForce(Vector3.right * shotPower);

 }

 

 void Update () {

 }

    private void OnCollisionEnter2D(Collision2D other) {

        if (other.gameObject.tag == “Monster”) {

            // 몬스터가 사라지도록 처리

            Destroy(other.gameObject);

            // 총알이 사라지도록 처리

            Destroy(gameObject);

        } else if (other.gameObject.tag == “Tile”) {

            // 총알이 사라지도록 처리

            Destroy(gameObject);

        }

    }

}

8. 프리팹 만들기

8-1. 프로젝트 뷰에 Prefabs 폴더 생성

8-2. 하이어라키 뷰의 Bullet_1 을 Prefabs 폴더 안으로 드래그앤드랍

8-3. 씬 뷰의 Bullet_1은 삭제

9. 소스 코드 수정

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BulletScript : MonoBehaviour {

    float shotPower = 500.0f;

   

 void Start () {

        if (transform.rotation.y == 0) {

            GetComponent<Rigidbody2D>().AddForce(Vector3.right * shotPower);

        } else {

            GetComponent<Rigidbody2D>().AddForce(Vector3.left * shotPower);

        }

       

 }

 

 void Update () {

 }

    private void OnCollisionEnter2D(Collision2D other) {

        if (other.gameObject.tag == “Monster”) {

            // 몬스터가 사라지도록 처리

            Destroy(other.gameObject);

            // 총알이 사라지도록 처리

            Destroy(gameObject);

        } else if (other.gameObject.tag == “Tile”) {

            // 총알이 사라지도록 처리

            Destroy(gameObject);

        }

    }

}

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class GetComponentAddForce : MonoBehaviour {

    public float jumpPower = 200.0f;

    public KeyCode keyLeft;

    public KeyCode keyRight;

    public KeyCode keyJump;

    public KeyCode keyAttack;

    // 외부에서 프리팹을 주입 가능하도록 변수 선언

    public GameObject bullet;

    // Use this for initialization

    void Start () {

    }

 

 // Update is called once per frame

 void Update () {

        if (Input.GetKey(keyLeft)) {

            transform.eulerAngles = new Vector3(0, 180, 0);

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

        } else if (Input.GetKey(keyRight)) {

            transform.eulerAngles = new Vector3(0, 0, 0);

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

        }

        if (Input.GetKeyDown(keyJump)) {

            GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumpPower);

        }

        if (Input.GetKeyDown(keyAttack)) {

            if (transform.rotation.y == 0) {

                Instantiate(bullet, transform.position + Vector3.right * 1.0f, transform.rotation);

            } else {

                Instantiate(bullet, transform.position + Vector3.left * 1.0f, transform.rotation);

            }

        }

    }

}

10. 우측 인스펙터 뷰 keyAttack 항목에 키보드 q 대입

11. 우측 인스펙터 뷰 bullet 항목에 프리팹 폴더 내의 Bullet1을 드래그앤드랍하여 대입