복습: 가장 가까운 코인
Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 67개 중 47번째.
챌린지
중급플레이어에게 코인 레이더를 추가하세요. 화살표 키로는 이미 플레이어를 움직입니다. 다음을 추가하세요. 스페이스 키를 누를 때마다 Coin 태그가 지정된 가장 가까운 오브젝트의 이름을 Nearest coin: Silver와 같이 기록합니다.
- 코인마다 이름이 다르며, 바위는 코인이 아닙니다.
- 코인은 줍으면 사라집니다(
SetActive(false)로 숨겨집니다). 따라서Start()에서 한 번만 검색하지 말고, 스페이스 키를 누를 때마다 코인을 검색하세요.
플레이를 누르고 주변을 돌아다니며 스페이스 키를 누른 다음, 확인을 누르세요.
직접 해보기
using UnityEngine;
public class CoinRadar : MonoBehaviour
{
[SerializeField] private float speed = 4f;
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += new Vector3(0, 0, speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.position -= new Vector3(0, 0, speed * Time.deltaTime);
}
// Space: 가장 가까운 코인의 이름을 로그에 기록합니다.
}
}