Start()
: 게임 내에서 해당 명령을 한 번만 실행Update()
: 해당 명령을 매 프레임마다 실행Start()
함수 내에서 작성 = 게임 내 한 번만 이동Update()
함수 내에서 작성 = 매 프레임마다 입력한 좌표 수만큼 이동 (연속 이동)f
를 붙여야 한다.c#
에서는 코드의 한 줄이 끝날때마다 ;
을 반드시 붙여야 한다.변수에 할당할 값의 자료형
변수명
= 값
;
직렬화
- 특정 객체(데이터)를 바이트의 나열로 바꿔서 파일이나 네트워크통신으로 Stream 가능하게 해주는 것
- Deserialize(역직렬화) : 직렬화된 바이트의 나열을 원래 객체(데이터)로 바꿔주는 것
- 즉 바이너리 데이터와 객체 데이터 사이의 인코딩, 디코딩
- 어떤 데이터를 전송하기 위해 재구성 가능한 형식으로 변환하는 것
- 이용하던(이용할) 데이터를 재사용/복원 하기 위한 과정
- 직렬화 방식 : 텍스트 기반 직렬화(JSON Serialization), 바이너리 기반 직렬화
- 수신자와 송신자가 동일한 프로토콜만 사용하면 어느 방법이든 동일하게 사용 가능
SerializeFiled 어트리뷰트
Inspector
에서 정상적으로 표시되며 여기서 간편하게 수정할 수 있다. 그러나 Inspector
에서 변경한 변수의 값은 스크립트에 동기화되지는 않으니 주의해야한다.C# 스크립트 | Inspector |
---|---|
![]() | ![]() |
[SerializeField]
속성을 가져야 한다.class MyClass{ public int serializeNum1;
// or [SerializeField] private int serializeNum2 }
[SerializeField]
속성을 가졌다면 구조체와 class도 가능Edit
- Project Settings
- Input Mangager
에서 유니티 Input API
로 조정할 수 있는 것과 이들의 조정방법을 볼 수 있다.controls | details |
---|---|
![]() | ![]() |
속도 조절 변수 할당
- 이동 함수 파라미터 값에 곱함
- Inspector에서 조절
Window
- Package Manager
- Cinemachine
installMain Camera
의 Inspector
에서 Cinemachine Brain
component 추가Cinemachine
- Create Virtual Camera
로 가상 카메라 생성 (메인 카메라의 브레인으로 추가된 가상 팔로우 카메라)Virtual Follow Camera
의 Inspector
설정Saving During Play
: 플레이모드에서 바꾼 설정값을 그대로 반영하고 싶을 때 사용Follow
: 플레이어/개체를 고정된 위치에서 따라다님Body
- Framing Transposer
: 선택한 카메라 프레임 안에 있는 개체를 따라다니면서 찍는 것Camera Distance
: 개체와 카메라의 거리 조절*Game창의 노이즈 제거 :
Hierarchy
에서Virtual Follow Camera
선택 해제
충돌 조건1.
Box Collider
충돌 조건2.
Rigid body
Constraints
을 통해 위치와 회전을 고정method(=Function)는 코드 블럭을 실행해 게임이 무언가를 하게 만드는 것
실행 방법 : 선언(Declaring) & 부르기(Calling)
type + name
(직관적이고 명확한 이름), 아무것도 반환하지 않는다면 void
(type + name)
, 없으면 비워두기{}
안에 실행할 것에 대한 코드 기재행위를 지시하는 문을 작성할 때는 코드를 반드시 ;
로 끝낼 것
Start()
& Update()
-> Callbacks
무엇인가에 부딪히면 유니티의 콜백(callback) 시스템이 충돌이 일어났을 때의 행동을 지시하는 OnCollisionEnter
를 호출한다.
Script | Unity |
---|---|
![]() | ![]() |
![]() | ![]() |
<>
안의 component를 불러오는 메소드
🔥Warning🔥
Unity에서 script를 적용할 때 반드시 오브젝트의Inspector
에서 component로
추가할 것
Script | Unity |
---|---|
![]() | ![]() |
Scorer
생성Player
의 Inspector
에 추가(Component
추가)//스코어 안내 스크립트 및 코드 추가//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scorer : MonoBehaviour
{
int hits = 0;
private void OnCollisionEnter(Collision other)
{
hits++; //hits = hits + 1; => 부딪힐 때마다 +1
Debug.Log("You've bumped into a thing this many times: " + hits); //부딪힌 횟수 알려주기
}
Wall
를 복붙해 이와 같은 조건의 장애물 만들기// Dropper.cs //
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dropper : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(Time.time); // 매 프레임마다 게임 시작으로부터 몇 초가 경과되었는지 알려줌
}
}
// If문 사용해 오브젝트(Dropper)가 지정시간 이후 떨어지게 하기//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dropper : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time > 3)
{
Debug.Log("3 seconds has elapsed");
}
}
}
Add Component
)캐싱
: 자주 사용되는 데이터나 정보를 필요할 때 쉽게 접근할 수 있도록 메모리에 저장하는 기술
// 지정 시간 이후에 색,중력 생겨 오브젝트(Dropper) 떨어지게 하기 //
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dropper : MonoBehaviour
{
MeshRenderer renderer;
Rigidbody rigidbody;
[SerializeField] float timeToWait = 2f;
// Start is called before the first frame update
void Start()
{
renderer = GetComponent<MeshRenderer>(); // 참조 캐싱
rigidbody = GetComponent<Rigidbody>();
renderer.enabled = false; // 떨어지는 오브젝트의 Mesh Renderer 해제 (보이지 않도록 함)
rigidbody.useGravity = false; // 중력 사용 해제
}
// Update is called once per frame
void Update()
{
if (Time.time > timeToWait)
{
renderer.enabled = true; // 떨어지는 오브젝트의 Mesh Renderer ON (보이도록 함)
rigidbody.useGravity = true; // 중력 사용
}
}
}
Dropper
에 ObjectHit.cs
스크립트 부착한 후,
Dropper
가 떨어질 때 바닥과 부딪힐 때가 아닌 Player
와 부딪힐 경우에만
색이 변하게 하기 위해 ObjectHit.cs
코드 수정
ObjectHit.cs
코드 수정using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectHit : MonoBehaviour
{
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == "Player")
// other = 부딪힌 물체
// Player tag의 오브젝트와 부딪힌 경우에만 아래 코드 실행
{
GetComponent<MeshRenderer>().material.color = Color.red;
}
}
}
Player
와 부딪힌 경우 Tag
바꿔주기
ObjectHit.cs
코드 추가using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectHit : MonoBehaviour
{
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == "Player")
{
GetComponent<MeshRenderer>().material.color = Color.red;
gameObject.tag = "Hit";
//앞에 아무것도 명시하지 않았으므로 이 스크립트가 부착된 게임 개체에 적용됨
//해당 개체가 부딪힐 경우 tag가 Hit로 바뀜
}
}
}
한 번 부딪힌 Obstacle은 다시 부딪혀도 더이상 스코어가 추가되지 않도록 제한
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Scorer : MonoBehaviour
{
int hits = 0;
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag != "Hit") // 한 번도 부딪히지 않은 경우(not Hit)에만 스코어 추가
{
hits++; //hits = hits + 1;
Debug.Log("You've bumped into a thing this many times: " + hits);
}
}
}
Spinner
개체와 스크립트 생성Spinner
개체에 ObjectHit
, Spinner
스크립트 부착Spinner
스크립트 작성```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spinner : MonoBehaviour
{
[SerializeField] float xAngle = 0;
[SerializeField] float yAngle = 0;
[SerializeField] float zAngle = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate(xAngle, yAngle, zAngle);
}
}
```
Assets
파일 정리Hierarchy
파일 정리Prefabs
파일에 드래그*오브젝트 중심축 기준
Global | Local |
---|---|
![]() | ![]() |