Menu
CoddyTech

Recap: Nearest Coin

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 47 of 67.

challenge icon

Challenge

Medium

Give the player a coin radar. The arrows already move the player. Add this: each press of Space logs the name of the nearest object tagged Coin, as Nearest coin: Silver.

  • The coins have different names, and the rock is not a coin.
  • Coins disappear when they are picked up (they are hidden with SetActive(false)), so search for the coins at each press, not once in Start().

Press Play, drive around and press Space, 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.
    }
}

All lessons in Unity Scripting Basics