Component
- component : 게임 오브젝트에 붙이는 기능
- Transform : 게임 오브젝트의 위치, 회전, 크기정보. 모든 게임 오브젝트가 가지고 있는 컴포넌트
- Mesh Filter : 게임 오브젝트의 모양 형태 데이터
- Mesh Renderer : 게임 오브젝트의 메쉬를 그리는 컴포넌트
Component 접근, 추가
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class ComponentStudy : MonoBehaviour
{
public GameObject targetObj; //GameObject 타입의 변수 생성
public Transform destination; // == GameObject.Transform
void Start()
{
/*
this.gameObject -> 자기 자신 접근
this 생략 가능
*/
gameObject.name = "empty object"; //자기 자신의 이름을 empty object로 변경
this.GetComponent<MeshRenderer>().enabled = false; //자기 자신의 MeshRender 비활성화
gameObject.AddComponent<BoxCollider>(); //BoxCollider 컴포넌트 추가
transform.position = destination.position;
/*
어떤 오브젝트가 갖고있는 컴포넌트 접근하는 방법 -> GetComponent 사용
어떤 대상. GetComponet<컴포넌트 이름>().함수 or 변수
*/
targetObj.name = "TargetObj";
targetObj.GetComponent<MeshRenderer>().enabled = false;
targetObj.GetComponent<CapsuleCollider>().enabled = false;
}
void OnEnable() //활성화 될 때마다 실행
{
transform.position += transform.forward; // 활성화 될 때 마다 앞으로 1씩 이동
}
}
캐릭터 이동
- GetKey, GetMouseButton
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputStudy : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.W)) // W 키 누른 순간
{
Debug.Log("W");
}
if (Input.GetKey(KeyCode.W)) // W 키 누르는 동안
{
Debug.Log("W");
}
if (Input.GetKeyUp(KeyCode.W)) // W 키를 떼는 순간
{
Debug.Log("W");
}
if (Input.GetKeyDown(KeyCode.Space)) // 스페이스키
{
Debug.Log("Space");
}
if (Input.GetKeyDown(KeyCode.Return)) // 엔터키
{
Debug.Log("Return");
}
if (Input.GetMouseButtonDown(0)) // 마우스 왼쪽 버튼을 누르기 시작
{
Debug.Log("마우스 왼쪽 버튼을 누르기 시작");
}
if (Input.GetMouseButton(0)) // 마우스 왼쪽 버튼을 누르는 중
{
Debug.Log("마우스 왼쪽 버튼을 누르는 중");
}
}
}
- InputManager에서 미리 만들어진 입력을 활용한 이동
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class Movement : MonoBehaviour
{
private Transform myTransform;
public float moveSpeed = 1f;
void Start()
{
myTransform = this.transform;
}
void Update()
{
float h = Input.GetAxis("Horizontal"); //좌,우 이동
float v = Input.GetAxis("Vertical"); //앞,뒤 이동
Vector3 dir = new Vector3(h, 0, v).normalized; //대각선 이동 시 크기가 1보다 커지기 때문에 normalized로 정규화
Debug.Log(dir);
transform.position += dir * moveSpeed * Time.deltaTime;
}
}
'TIL' 카테고리의 다른 글
[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 7일차 Door Animation, 중복 점프 방지 (0) | 2024.11.27 |
---|---|
[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 6일차 Rotation, RigidBody (0) | 2024.11.26 |
[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 4일차 Prefab, Material (0) | 2024.11.25 |
[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 3일차 Scene View (1) | 2024.11.23 |
[멋쟁이사자처럼 부트캠프 TIL 회고] 유니티 게임개발 3기 1-2일차 유니티 게임 엔진 (1) | 2024.11.23 |