Menu
CoddyTech

Recap: Nearest Coin

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 61 of 85.

This recap puts the chapter together: a search by tag at the moment it is needed, a loop over what it finds, and the distance to each one.

challenge icon

Challenge

Medium

Give the player a coin radar: Space names the nearest coin.

  1. On Space, start with GameObject nearest = null; and float best = Mathf.Infinity;.
  2. For each coin in GameObject.FindGameObjectsWithTag("Coin"), keep it when its distance to the player is below best.
  3. Log "Nearest coin: " + nearest.name.

Press Play, drive and press Space: the Console shows Nearest coin: Silver. Then Check.

Try it yourself

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: log the name of the nearest coin.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground