본문 바로가기
Development/C#

[멋쟁이사자처럼 부트캠프 TIL 회고] Unity 게임 개발 3기 5일차

by Mobics 2024. 11. 25.

 

목차


    Unity

    Component

    : GameObject에 붙이는 기능

    Transform

    : GameObject의 위치, 회전, 크기 정보

    ※ Scene 상에 존재하기 위해서 모든 GameObject가 갖고 있는 Component

    Mesh Filter

    : Mesh는 GameObject의 모양 또는 형태 데이터

    Mesh Renderer

    : GameObject의 Mesh를 그리는 Component

     

    ※ Active vs Render

    : Active는 존재 자체를 끄고 켜는 거지만, Render는 존재하는 것을 그릴지 말지 정하는 것

    --> 벽을 만들고 벽의 Render를 Off하면 투명벽이 됨


    Unity C#

    Code로 Component 접근

    : GetComponent<컴포넌트 이름>().내부 변수 or 내부 함수;

     

    GameObject 이름 바꾸기

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ComponentStudy : MonoBehaviour
    {
        public GameObject targetObj; // 어떤 대상을 담는 접시
    
        void Start()
        {
            gameObject.name = "빈 게임 오브젝트"; // 자기 자신의 이름 변경
            
            targetObj.name = "Other GameObject";
        }
    }

     

    실행 전

     

    실행 후

     

    Object 할당 후, 실행 전

     

    Object 할당 후, 실행 후

     

    MeshRenderer에 접근하여 비활성화 하기

    : GetComponent<MeshRenderer>().enabled = false

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ComponentStudy : MonoBehaviour
    {
        public GameObject targetObj; // 어떤 대상을 담는 접시
    
        void Start()
        {
            gameObject.name = "빈 게임 오브젝트"; // 자기 자신의 이름 변경
            
            targetObj.name = "Other GameObject";
            
            gameObject.GetComponent<MeshRenderer>().enabled = false;
        }
    }

     

    실행 전

     

    실행 후

     

    AddComponent

    : Component 추가 기능

    : AddComponent<컴포넌트 이름>();

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ComponentStudy : MonoBehaviour
    {
        public GameObject targetObj; // 어떤 대상을 담는 접시
    
        void Start()
        {
            gameObject.name = "빈 게임 오브젝트"; // 자기 자신의 이름 변경
            
            targetObj.name = "Other GameObject";
            
            gameObject.GetComponent<MeshRenderer>().enabled = false;
            
            gameObject.AddComponent<BoxCollider>();
        }
    }

     

    실행 전

     

    실행 후

     

    Code로 Transform 접근하여 이동시키기

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ComponentStudy : MonoBehaviour
    {
        void Start()
        {
            transform.position += Vector3.forward;
            // this.gameObject.transform.position += Vector3.forward;
            // transform은 모든 gameObject가 가지고 있기 때문에 this.gameobject는 생략 가능
        }
        
        void OnEnable() // 존재를 On할 때마다 실행되는 유니티 기본 함수
        {
        	transform.position += Vector3.forward;
        }
    }

     

    원하는 목적지로 이동

     

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class ComponentStudy : MonoBehaviour
    {
        public Transform destination; // 목적지 오브젝트
    
        void Start()
        {
        	// 자기 자신의 Transform의 위치를 destination의 위치로 할당한다.
            transform.position = destination.position;
        }
    }

     

    목적지 위치

     

    실행 후, 이동한 모습

     

    자주 사용하는 벡터에 대한 명칭

     

    어몽어스 캐릭터 움직이기+

     

    ※ 마우스 입력

    • GetMouseButtonDown : 마우스 버튼을 누를 때
    • GetMouseButton : 마우스 버튼을 누르고 있을 때
    • GetMouseButtonUp : 마우스 버튼을 뗄 때
    • 0 : 왼쪽 클릭
    • 1 : 오른쪽 클릭
    • 2 : 휠 클릭
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class InputStudy : MonoBehaviour
    {
        void Update()
        {
            if (Input.GetMouseButtonDown(0)) // 마우스 왼쪽 버튼을 누르기 시작
                Debug.Log("마우스 왼쪽 버튼을 누르기 시작");
            if (Input.GetMouseButton(0)) // 마우스 왼쪽 버튼을 누르는 중
                Debug.Log("마우스 왼쪽 버튼을 누르는 중");
        }
    }

     

    Position 이동 vs Translate 이동

    : Position 이동은 Global 좌표계를 따라 이동하지만 Translate 이동은 Local 좌표계를 따라 이동

     

    ※ Translate 이동 사용법

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f;
    
        void Update()
        {
            if (Input.GetKey(KeyCode.W))
            {
                transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
            }
    
            if (Input.GetKey(KeyCode.S))
            {
                transform.Translate(Vector3.back * Time.deltaTime * moveSpeed);
            }
    
            if (Input.GetKey(KeyCode.A))
            {
                transform.Translate(Vector3.left * Time.deltaTime * moveSpeed);
            }
    
            if (Input.GetKey(KeyCode.D))
            {
                transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
            }
        }
    }

     

    InputManager에서 미리 만들어진 입력을 활용한 이동

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f;
    
        void Update()
        {
            float h = Input.GetAxis("Horizontal"); // 오른쪽, 왼쪽 이동
            float v = Input.GetAxis("Vertical"); // 앞, 뒤 이동
            
            Vector3 dir = new Vector3(h, 0, v); // 입력한 값으로 Vector3 선언 및 할당
            Debug.Log(dir);
            
            transform.position += dir * moveSpeed * Time.deltaTime;
        }
    }

    ※ 대각선으로 이동할 때 속도가 더 빨라지는 문제 발생

     

    정규화(Normalized)

    : 0 ~ 1 값으로 단위화

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f;
    
        void Update()
        {
            float h = Input.GetAxis("Horizontal"); // 오른쪽, 왼쪽 이동
            float v = Input.GetAxis("Vertical"); // 앞, 뒤 이동
            
            Vector3 dir = new Vector3(h, 0, v).normalized; // 정규화
            Debug.Log(dir);
            
            transform.position += dir * moveSpeed * Time.deltaTime;
        }
    }

     

     

    ※ 만약에 가속하는 기능을 넣을 경우

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f; // public으로 선언한 속도 변수
    
        void Update()
        {
            float h = Input.GetAxis("Horizontal"); // 오른쪽, 왼쪽 이동
            float v = Input.GetAxis("Vertical"); // 앞, 뒤 이동
    
            Vector3 dir = new Vector3(h, 0, v);
    
            transform.position += dir * moveSpeed * Time.deltaTime;
    
            // 속도 증가 -> Speed 변경!
            if (Input.GetKey(KeyCode.LeftShift)) // Left Shift를 누르고 있다면
            {
                moveSpeed = 7.5f; // 가속 -> 뛸 때
            }
            else if (Input.GetKeyUp(KeyCode.LeftShift))
            {
                moveSpeed = 5f; // 다시 감속 -> 걸을 때
            }
    
        }
    }

    Frame과 Delta Time

    Frame : 화면에 한 장의 화면을 렌더링한 것

    FPS (Frame Per Second) : 초당 프레임 실행 횟수

     

    Delta Time