Menu
CoddyTech

복습: 가장 가까운 코인

Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 85개 중 61번째.

이번 복습에서는 필요한 순간에 태그로 검색하고, 검색된 항목을 반복문으로 살펴보며, 각 항목까지의 거리를 구하는 내용을 종합합니다.

challenge icon

챌린지

중급

플레이어에게 코인 레이더를 만들어 주세요. 스페이스바를 누르면 가장 가까운 코인의 이름을 표시합니다.

  1. 스페이스바를 누르면 GameObject nearest = null;과 float best = Mathf.Infinity;로 시작하세요.
  2. GameObject.FindGameObjectsWithTag("Coin")의 각 코인에 대해, 플레이어와의 거리가 best보다 작으면 해당 코인을 저장하세요.
  3. "Nearest coin: " + nearest.name을 로그로 출력하세요.

‘플레이’를 누르고 이동한 다음 스페이스바를 누르세요. Console에 Nearest coin: Silver가 표시됩니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

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: 가장 가까운 코인의 이름을 로그에 기록합니다.
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Unity 스크립팅 기초의 모든 레슨

직접 연습해 보세요: Unity 플레이그라운드